]> git.proxmox.com Git - mirror_zfs.git/blob - cmd/zfs/zfs_main.c
Remove complicated libspl assert wrappers
[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 (void) nvlist_lookup_uint64(lnvl, propname,
2304 &lv64);
2305 (void) nvlist_lookup_uint64(rnvl, propname,
2306 &rv64);
2307 if (rv64 != lv64)
2308 rc = (rv64 < lv64) ? 1 : -1;
2309 } else {
2310 (void) nvlist_lookup_string(lnvl, propname,
2311 &lvstr);
2312 (void) nvlist_lookup_string(rnvl, propname,
2313 &rvstr);
2314 rc = strcmp(lvstr, rvstr);
2315 }
2316 break;
2317 case ZFS_PROP_USED:
2318 case ZFS_PROP_QUOTA:
2319 if (!us_populated)
2320 break;
2321 if (prop == ZFS_PROP_USED)
2322 propname = "used";
2323 else
2324 propname = "quota";
2325 (void) nvlist_lookup_uint64(lnvl, propname, &lv64);
2326 (void) nvlist_lookup_uint64(rnvl, propname, &rv64);
2327 if (rv64 != lv64)
2328 rc = (rv64 < lv64) ? 1 : -1;
2329 break;
2330 default:
2331 break;
2332 }
2333
2334 if (rc != 0) {
2335 if (rc < 0)
2336 return (reverse ? 1 : -1);
2337 else
2338 return (reverse ? -1 : 1);
2339 }
2340 }
2341
2342 /*
2343 * If entries still seem to be the same, check if they are of the same
2344 * type (smbentity is added only if we are doing SID to POSIX ID
2345 * translation where we can have duplicate type/name combinations).
2346 */
2347 if (nvlist_lookup_boolean_value(lnvl, "smbentity", &lvb) == 0 &&
2348 nvlist_lookup_boolean_value(rnvl, "smbentity", &rvb) == 0 &&
2349 lvb != rvb)
2350 return (lvb < rvb ? -1 : 1);
2351
2352 return (0);
2353 }
2354
2355 static inline const char *
2356 us_type2str(unsigned field_type)
2357 {
2358 switch (field_type) {
2359 case USTYPE_PSX_USR:
2360 return ("POSIX User");
2361 case USTYPE_PSX_GRP:
2362 return ("POSIX Group");
2363 case USTYPE_SMB_USR:
2364 return ("SMB User");
2365 case USTYPE_SMB_GRP:
2366 return ("SMB Group");
2367 default:
2368 return ("Undefined");
2369 }
2370 }
2371
2372 static int
2373 userspace_cb(void *arg, const char *domain, uid_t rid, uint64_t space)
2374 {
2375 us_cbdata_t *cb = (us_cbdata_t *)arg;
2376 zfs_userquota_prop_t prop = cb->cb_prop;
2377 char *name = NULL;
2378 char *propname;
2379 char sizebuf[32];
2380 us_node_t *node;
2381 uu_avl_pool_t *avl_pool = cb->cb_avl_pool;
2382 uu_avl_t *avl = cb->cb_avl;
2383 uu_avl_index_t idx;
2384 nvlist_t *props;
2385 us_node_t *n;
2386 zfs_sort_column_t *sortcol = cb->cb_sortcol;
2387 unsigned type = 0;
2388 const char *typestr;
2389 size_t namelen;
2390 size_t typelen;
2391 size_t sizelen;
2392 int typeidx, nameidx, sizeidx;
2393 us_sort_info_t sortinfo = { sortcol, cb->cb_numname };
2394 boolean_t smbentity = B_FALSE;
2395
2396 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
2397 nomem();
2398 node = safe_malloc(sizeof (us_node_t));
2399 uu_avl_node_init(node, &node->usn_avlnode, avl_pool);
2400 node->usn_nvl = props;
2401
2402 if (domain != NULL && domain[0] != '\0') {
2403 #ifdef HAVE_IDMAP
2404 /* SMB */
2405 char sid[ZFS_MAXNAMELEN + 32];
2406 uid_t id;
2407 uint64_t classes;
2408 int err;
2409 directory_error_t e;
2410
2411 smbentity = B_TRUE;
2412
2413 (void) snprintf(sid, sizeof (sid), "%s-%u", domain, rid);
2414
2415 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2416 type = USTYPE_SMB_GRP;
2417 err = sid_to_id(sid, B_FALSE, &id);
2418 } else {
2419 type = USTYPE_SMB_USR;
2420 err = sid_to_id(sid, B_TRUE, &id);
2421 }
2422
2423 if (err == 0) {
2424 rid = id;
2425 if (!cb->cb_sid2posix) {
2426 e = directory_name_from_sid(NULL, sid, &name,
2427 &classes);
2428 if (e != NULL)
2429 directory_error_free(e);
2430 if (name == NULL)
2431 name = sid;
2432 }
2433 }
2434 #else
2435 nvlist_free(props);
2436 free(node);
2437
2438 return (-1);
2439 #endif /* HAVE_IDMAP */
2440 }
2441
2442 if (cb->cb_sid2posix || domain == NULL || domain[0] == '\0') {
2443 /* POSIX or -i */
2444 if (prop == ZFS_PROP_GROUPUSED || prop == ZFS_PROP_GROUPQUOTA) {
2445 type = USTYPE_PSX_GRP;
2446 if (!cb->cb_numname) {
2447 struct group *g;
2448
2449 if ((g = getgrgid(rid)) != NULL)
2450 name = g->gr_name;
2451 }
2452 } else {
2453 type = USTYPE_PSX_USR;
2454 if (!cb->cb_numname) {
2455 struct passwd *p;
2456
2457 if ((p = getpwuid(rid)) != NULL)
2458 name = p->pw_name;
2459 }
2460 }
2461 }
2462
2463 /*
2464 * Make sure that the type/name combination is unique when doing
2465 * SID to POSIX ID translation (hence changing the type from SMB to
2466 * POSIX).
2467 */
2468 if (cb->cb_sid2posix &&
2469 nvlist_add_boolean_value(props, "smbentity", smbentity) != 0)
2470 nomem();
2471
2472 /* Calculate/update width of TYPE field */
2473 typestr = us_type2str(type);
2474 typelen = strlen(gettext(typestr));
2475 typeidx = us_field_index("type");
2476 if (typelen > cb->cb_width[typeidx])
2477 cb->cb_width[typeidx] = typelen;
2478 if (nvlist_add_uint32(props, "type", type) != 0)
2479 nomem();
2480
2481 /* Calculate/update width of NAME field */
2482 if ((cb->cb_numname && cb->cb_sid2posix) || name == NULL) {
2483 if (nvlist_add_uint64(props, "name", rid) != 0)
2484 nomem();
2485 namelen = snprintf(NULL, 0, "%u", rid);
2486 } else {
2487 if (nvlist_add_string(props, "name", name) != 0)
2488 nomem();
2489 namelen = strlen(name);
2490 }
2491 nameidx = us_field_index("name");
2492 if (namelen > cb->cb_width[nameidx])
2493 cb->cb_width[nameidx] = namelen;
2494
2495 /*
2496 * Check if this type/name combination is in the list and update it;
2497 * otherwise add new node to the list.
2498 */
2499 if ((n = uu_avl_find(avl, node, &sortinfo, &idx)) == NULL) {
2500 uu_avl_insert(avl, node, idx);
2501 } else {
2502 nvlist_free(props);
2503 free(node);
2504 node = n;
2505 props = node->usn_nvl;
2506 }
2507
2508 /* Calculate/update width of USED/QUOTA fields */
2509 if (cb->cb_nicenum)
2510 zfs_nicenum(space, sizebuf, sizeof (sizebuf));
2511 else
2512 (void) snprintf(sizebuf, sizeof (sizebuf), "%llu",
2513 (u_longlong_t)space);
2514 sizelen = strlen(sizebuf);
2515 if (prop == ZFS_PROP_USERUSED || prop == ZFS_PROP_GROUPUSED) {
2516 propname = "used";
2517 if (!nvlist_exists(props, "quota"))
2518 (void) nvlist_add_uint64(props, "quota", 0);
2519 } else {
2520 propname = "quota";
2521 if (!nvlist_exists(props, "used"))
2522 (void) nvlist_add_uint64(props, "used", 0);
2523 }
2524 sizeidx = us_field_index(propname);
2525 if (sizelen > cb->cb_width[sizeidx])
2526 cb->cb_width[sizeidx] = sizelen;
2527
2528 if (nvlist_add_uint64(props, propname, space) != 0)
2529 nomem();
2530
2531 return (0);
2532 }
2533
2534 static void
2535 print_us_node(boolean_t scripted, boolean_t parsable, int *fields, int types,
2536 size_t *width, us_node_t *node)
2537 {
2538 nvlist_t *nvl = node->usn_nvl;
2539 char valstr[ZFS_MAXNAMELEN];
2540 boolean_t first = B_TRUE;
2541 int cfield = 0;
2542 int field;
2543 uint32_t ustype;
2544
2545 /* Check type */
2546 (void) nvlist_lookup_uint32(nvl, "type", &ustype);
2547 if (!(ustype & types))
2548 return;
2549
2550 while ((field = fields[cfield]) != USFIELD_LAST) {
2551 nvpair_t *nvp = NULL;
2552 data_type_t type;
2553 uint32_t val32;
2554 uint64_t val64;
2555 char *strval = NULL;
2556
2557 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
2558 if (strcmp(nvpair_name(nvp),
2559 us_field_names[field]) == 0)
2560 break;
2561 }
2562
2563 type = nvpair_type(nvp);
2564 switch (type) {
2565 case DATA_TYPE_UINT32:
2566 (void) nvpair_value_uint32(nvp, &val32);
2567 break;
2568 case DATA_TYPE_UINT64:
2569 (void) nvpair_value_uint64(nvp, &val64);
2570 break;
2571 case DATA_TYPE_STRING:
2572 (void) nvpair_value_string(nvp, &strval);
2573 break;
2574 default:
2575 (void) fprintf(stderr, "invalid data type\n");
2576 }
2577
2578 switch (field) {
2579 case USFIELD_TYPE:
2580 strval = (char *)us_type2str(val32);
2581 break;
2582 case USFIELD_NAME:
2583 if (type == DATA_TYPE_UINT64) {
2584 (void) sprintf(valstr, "%llu",
2585 (u_longlong_t) val64);
2586 strval = valstr;
2587 }
2588 break;
2589 case USFIELD_USED:
2590 case USFIELD_QUOTA:
2591 if (type == DATA_TYPE_UINT64) {
2592 if (parsable) {
2593 (void) sprintf(valstr, "%llu",
2594 (u_longlong_t) val64);
2595 } else {
2596 zfs_nicenum(val64, valstr,
2597 sizeof (valstr));
2598 }
2599 if (field == USFIELD_QUOTA &&
2600 strcmp(valstr, "0") == 0)
2601 strval = "none";
2602 else
2603 strval = valstr;
2604 }
2605 break;
2606 }
2607
2608 if (!first) {
2609 if (scripted)
2610 (void) printf("\t");
2611 else
2612 (void) printf(" ");
2613 }
2614 if (scripted)
2615 (void) printf("%s", strval);
2616 else if (field == USFIELD_TYPE || field == USFIELD_NAME)
2617 (void) printf("%-*s", (int) width[field], strval);
2618 else
2619 (void) printf("%*s", (int) width[field], strval);
2620
2621 first = B_FALSE;
2622 cfield++;
2623 }
2624
2625 (void) printf("\n");
2626 }
2627
2628 static void
2629 print_us(boolean_t scripted, boolean_t parsable, int *fields, int types,
2630 size_t *width, boolean_t rmnode, uu_avl_t *avl)
2631 {
2632 us_node_t *node;
2633 const char *col;
2634 int cfield = 0;
2635 int field;
2636
2637 if (!scripted) {
2638 boolean_t first = B_TRUE;
2639
2640 while ((field = fields[cfield]) != USFIELD_LAST) {
2641 col = gettext(us_field_hdr[field]);
2642 if (field == USFIELD_TYPE || field == USFIELD_NAME) {
2643 (void) printf(first ? "%-*s" : " %-*s",
2644 (int) width[field], col);
2645 } else {
2646 (void) printf(first ? "%*s" : " %*s",
2647 (int) width[field], col);
2648 }
2649 first = B_FALSE;
2650 cfield++;
2651 }
2652 (void) printf("\n");
2653 }
2654
2655 for (node = uu_avl_first(avl); node; node = uu_avl_next(avl, node)) {
2656 print_us_node(scripted, parsable, fields, types, width, node);
2657 if (rmnode)
2658 nvlist_free(node->usn_nvl);
2659 }
2660 }
2661
2662 static int
2663 zfs_do_userspace(int argc, char **argv)
2664 {
2665 zfs_handle_t *zhp;
2666 zfs_userquota_prop_t p;
2667 uu_avl_pool_t *avl_pool;
2668 uu_avl_t *avl_tree;
2669 uu_avl_walk_t *walk;
2670 char *delim;
2671 char deffields[] = "type,name,used,quota";
2672 char *ofield = NULL;
2673 char *tfield = NULL;
2674 int cfield = 0;
2675 int fields[256];
2676 int i;
2677 boolean_t scripted = B_FALSE;
2678 boolean_t prtnum = B_FALSE;
2679 boolean_t parsable = B_FALSE;
2680 boolean_t sid2posix = B_FALSE;
2681 int ret = 0;
2682 int c;
2683 zfs_sort_column_t *sortcol = NULL;
2684 int types = USTYPE_PSX_USR | USTYPE_SMB_USR;
2685 us_cbdata_t cb;
2686 us_node_t *node;
2687 us_node_t *rmnode;
2688 uu_list_pool_t *listpool;
2689 uu_list_t *list;
2690 uu_avl_index_t idx = 0;
2691 uu_list_index_t idx2 = 0;
2692
2693 if (argc < 2)
2694 usage(B_FALSE);
2695
2696 if (strcmp(argv[0], "groupspace") == 0)
2697 /* Toggle default group types */
2698 types = USTYPE_PSX_GRP | USTYPE_SMB_GRP;
2699
2700 while ((c = getopt(argc, argv, "nHpo:s:S:t:i")) != -1) {
2701 switch (c) {
2702 case 'n':
2703 prtnum = B_TRUE;
2704 break;
2705 case 'H':
2706 scripted = B_TRUE;
2707 break;
2708 case 'p':
2709 parsable = B_TRUE;
2710 break;
2711 case 'o':
2712 ofield = optarg;
2713 break;
2714 case 's':
2715 case 'S':
2716 if (zfs_add_sort_column(&sortcol, optarg,
2717 c == 's' ? B_FALSE : B_TRUE) != 0) {
2718 (void) fprintf(stderr,
2719 gettext("invalid field '%s'\n"), optarg);
2720 usage(B_FALSE);
2721 }
2722 break;
2723 case 't':
2724 tfield = optarg;
2725 break;
2726 case 'i':
2727 sid2posix = B_TRUE;
2728 break;
2729 case ':':
2730 (void) fprintf(stderr, gettext("missing argument for "
2731 "'%c' option\n"), optopt);
2732 usage(B_FALSE);
2733 break;
2734 case '?':
2735 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
2736 optopt);
2737 usage(B_FALSE);
2738 }
2739 }
2740
2741 argc -= optind;
2742 argv += optind;
2743
2744 if (argc < 1) {
2745 (void) fprintf(stderr, gettext("missing dataset name\n"));
2746 usage(B_FALSE);
2747 }
2748 if (argc > 1) {
2749 (void) fprintf(stderr, gettext("too many arguments\n"));
2750 usage(B_FALSE);
2751 }
2752
2753 /* Use default output fields if not specified using -o */
2754 if (ofield == NULL)
2755 ofield = deffields;
2756 do {
2757 if ((delim = strchr(ofield, ',')) != NULL)
2758 *delim = '\0';
2759 if ((fields[cfield++] = us_field_index(ofield)) == -1) {
2760 (void) fprintf(stderr, gettext("invalid type '%s' "
2761 "for -o option\n"), ofield);
2762 return (-1);
2763 }
2764 if (delim != NULL)
2765 ofield = delim + 1;
2766 } while (delim != NULL);
2767 fields[cfield] = USFIELD_LAST;
2768
2769 /* Override output types (-t option) */
2770 if (tfield != NULL) {
2771 types = 0;
2772
2773 do {
2774 boolean_t found = B_FALSE;
2775
2776 if ((delim = strchr(tfield, ',')) != NULL)
2777 *delim = '\0';
2778 for (i = 0; i < sizeof (us_type_bits) / sizeof (int);
2779 i++) {
2780 if (strcmp(tfield, us_type_names[i]) == 0) {
2781 found = B_TRUE;
2782 types |= us_type_bits[i];
2783 break;
2784 }
2785 }
2786 if (!found) {
2787 (void) fprintf(stderr, gettext("invalid type "
2788 "'%s' for -t option\n"), tfield);
2789 return (-1);
2790 }
2791 if (delim != NULL)
2792 tfield = delim + 1;
2793 } while (delim != NULL);
2794 }
2795
2796 if ((zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET)) == NULL)
2797 return (1);
2798
2799 if ((avl_pool = uu_avl_pool_create("us_avl_pool", sizeof (us_node_t),
2800 offsetof(us_node_t, usn_avlnode), us_compare, UU_DEFAULT)) == NULL)
2801 nomem();
2802 if ((avl_tree = uu_avl_create(avl_pool, NULL, UU_DEFAULT)) == NULL)
2803 nomem();
2804
2805 /* Always add default sorting columns */
2806 (void) zfs_add_sort_column(&sortcol, "type", B_FALSE);
2807 (void) zfs_add_sort_column(&sortcol, "name", B_FALSE);
2808
2809 cb.cb_sortcol = sortcol;
2810 cb.cb_numname = prtnum;
2811 cb.cb_nicenum = !parsable;
2812 cb.cb_avl_pool = avl_pool;
2813 cb.cb_avl = avl_tree;
2814 cb.cb_sid2posix = sid2posix;
2815
2816 for (i = 0; i < USFIELD_LAST; i++)
2817 cb.cb_width[i] = strlen(gettext(us_field_hdr[i]));
2818
2819 for (p = 0; p < ZFS_NUM_USERQUOTA_PROPS; p++) {
2820 if (((p == ZFS_PROP_USERUSED || p == ZFS_PROP_USERQUOTA) &&
2821 !(types & (USTYPE_PSX_USR | USTYPE_SMB_USR))) ||
2822 ((p == ZFS_PROP_GROUPUSED || p == ZFS_PROP_GROUPQUOTA) &&
2823 !(types & (USTYPE_PSX_GRP | USTYPE_SMB_GRP))))
2824 continue;
2825 cb.cb_prop = p;
2826 if ((ret = zfs_userspace(zhp, p, userspace_cb, &cb)) != 0)
2827 return (ret);
2828 }
2829
2830 /* Sort the list */
2831 if ((node = uu_avl_first(avl_tree)) == NULL)
2832 return (0);
2833
2834 us_populated = B_TRUE;
2835
2836 listpool = uu_list_pool_create("tmplist", sizeof (us_node_t),
2837 offsetof(us_node_t, usn_listnode), NULL, UU_DEFAULT);
2838 list = uu_list_create(listpool, NULL, UU_DEFAULT);
2839 uu_list_node_init(node, &node->usn_listnode, listpool);
2840
2841 while (node != NULL) {
2842 rmnode = node;
2843 node = uu_avl_next(avl_tree, node);
2844 uu_avl_remove(avl_tree, rmnode);
2845 if (uu_list_find(list, rmnode, NULL, &idx2) == NULL)
2846 uu_list_insert(list, rmnode, idx2);
2847 }
2848
2849 for (node = uu_list_first(list); node != NULL;
2850 node = uu_list_next(list, node)) {
2851 us_sort_info_t sortinfo = { sortcol, cb.cb_numname };
2852
2853 if (uu_avl_find(avl_tree, node, &sortinfo, &idx) == NULL)
2854 uu_avl_insert(avl_tree, node, idx);
2855 }
2856
2857 uu_list_destroy(list);
2858 uu_list_pool_destroy(listpool);
2859
2860 /* Print and free node nvlist memory */
2861 print_us(scripted, parsable, fields, types, cb.cb_width, B_TRUE,
2862 cb.cb_avl);
2863
2864 zfs_free_sort_columns(sortcol);
2865
2866 /* Clean up the AVL tree */
2867 if ((walk = uu_avl_walk_start(cb.cb_avl, UU_WALK_ROBUST)) == NULL)
2868 nomem();
2869
2870 while ((node = uu_avl_walk_next(walk)) != NULL) {
2871 uu_avl_remove(cb.cb_avl, node);
2872 free(node);
2873 }
2874
2875 uu_avl_walk_end(walk);
2876 uu_avl_destroy(avl_tree);
2877 uu_avl_pool_destroy(avl_pool);
2878
2879 return (ret);
2880 }
2881
2882 /*
2883 * list [-Hp][-r|-d max] [-o property[,...]] [-s property] ... [-S property]
2884 * [-t type[,...]] [filesystem|volume|snapshot] ...
2885 *
2886 * -H Scripted mode; elide headers and separate columns by tabs
2887 * -p Display values in parsable (literal) format.
2888 * -r Recurse over all children
2889 * -d Limit recursion by depth.
2890 * -o Control which fields to display.
2891 * -s Specify sort columns, descending order.
2892 * -S Specify sort columns, ascending order.
2893 * -t Control which object types to display.
2894 *
2895 * When given no arguments, list all filesystems in the system.
2896 * Otherwise, list the specified datasets, optionally recursing down them if
2897 * '-r' is specified.
2898 */
2899 typedef struct list_cbdata {
2900 boolean_t cb_first;
2901 boolean_t cb_literal;
2902 boolean_t cb_scripted;
2903 zprop_list_t *cb_proplist;
2904 } list_cbdata_t;
2905
2906 /*
2907 * Given a list of columns to display, output appropriate headers for each one.
2908 */
2909 static void
2910 print_header(list_cbdata_t *cb)
2911 {
2912 zprop_list_t *pl = cb->cb_proplist;
2913 char headerbuf[ZFS_MAXPROPLEN];
2914 const char *header;
2915 int i;
2916 boolean_t first = B_TRUE;
2917 boolean_t right_justify;
2918
2919 for (; pl != NULL; pl = pl->pl_next) {
2920 if (!first) {
2921 (void) printf(" ");
2922 } else {
2923 first = B_FALSE;
2924 }
2925
2926 right_justify = B_FALSE;
2927 if (pl->pl_prop != ZPROP_INVAL) {
2928 header = zfs_prop_column_name(pl->pl_prop);
2929 right_justify = zfs_prop_align_right(pl->pl_prop);
2930 } else {
2931 for (i = 0; pl->pl_user_prop[i] != '\0'; i++)
2932 headerbuf[i] = toupper(pl->pl_user_prop[i]);
2933 headerbuf[i] = '\0';
2934 header = headerbuf;
2935 }
2936
2937 if (pl->pl_next == NULL && !right_justify)
2938 (void) printf("%s", header);
2939 else if (right_justify)
2940 (void) printf("%*s", (int)pl->pl_width, header);
2941 else
2942 (void) printf("%-*s", (int)pl->pl_width, header);
2943 }
2944
2945 (void) printf("\n");
2946 }
2947
2948 /*
2949 * Given a dataset and a list of fields, print out all the properties according
2950 * to the described layout.
2951 */
2952 static void
2953 print_dataset(zfs_handle_t *zhp, list_cbdata_t *cb)
2954 {
2955 zprop_list_t *pl = cb->cb_proplist;
2956 boolean_t first = B_TRUE;
2957 char property[ZFS_MAXPROPLEN];
2958 nvlist_t *userprops = zfs_get_user_props(zhp);
2959 nvlist_t *propval;
2960 char *propstr;
2961 boolean_t right_justify;
2962
2963 for (; pl != NULL; pl = pl->pl_next) {
2964 if (!first) {
2965 if (cb->cb_scripted)
2966 (void) printf("\t");
2967 else
2968 (void) printf(" ");
2969 } else {
2970 first = B_FALSE;
2971 }
2972
2973 if (pl->pl_prop == ZFS_PROP_NAME) {
2974 (void) strlcpy(property, zfs_get_name(zhp),
2975 sizeof (property));
2976 propstr = property;
2977 right_justify = zfs_prop_align_right(pl->pl_prop);
2978 } else if (pl->pl_prop != ZPROP_INVAL) {
2979 if (zfs_prop_get(zhp, pl->pl_prop, property,
2980 sizeof (property), NULL, NULL, 0,
2981 cb->cb_literal) != 0)
2982 propstr = "-";
2983 else
2984 propstr = property;
2985 right_justify = zfs_prop_align_right(pl->pl_prop);
2986 } else if (zfs_prop_userquota(pl->pl_user_prop)) {
2987 if (zfs_prop_get_userquota(zhp, pl->pl_user_prop,
2988 property, sizeof (property), cb->cb_literal) != 0)
2989 propstr = "-";
2990 else
2991 propstr = property;
2992 right_justify = B_TRUE;
2993 } else if (zfs_prop_written(pl->pl_user_prop)) {
2994 if (zfs_prop_get_written(zhp, pl->pl_user_prop,
2995 property, sizeof (property), cb->cb_literal) != 0)
2996 propstr = "-";
2997 else
2998 propstr = property;
2999 right_justify = B_TRUE;
3000 } else {
3001 if (nvlist_lookup_nvlist(userprops,
3002 pl->pl_user_prop, &propval) != 0)
3003 propstr = "-";
3004 else
3005 verify(nvlist_lookup_string(propval,
3006 ZPROP_VALUE, &propstr) == 0);
3007 right_justify = B_FALSE;
3008 }
3009
3010 /*
3011 * If this is being called in scripted mode, or if this is the
3012 * last column and it is left-justified, don't include a width
3013 * format specifier.
3014 */
3015 if (cb->cb_scripted || (pl->pl_next == NULL && !right_justify))
3016 (void) printf("%s", propstr);
3017 else if (right_justify)
3018 (void) printf("%*s", (int)pl->pl_width, propstr);
3019 else
3020 (void) printf("%-*s", (int)pl->pl_width, propstr);
3021 }
3022
3023 (void) printf("\n");
3024 }
3025
3026 /*
3027 * Generic callback function to list a dataset or snapshot.
3028 */
3029 static int
3030 list_callback(zfs_handle_t *zhp, void *data)
3031 {
3032 list_cbdata_t *cbp = data;
3033
3034 if (cbp->cb_first) {
3035 if (!cbp->cb_scripted)
3036 print_header(cbp);
3037 cbp->cb_first = B_FALSE;
3038 }
3039
3040 print_dataset(zhp, cbp);
3041
3042 return (0);
3043 }
3044
3045 static int
3046 zfs_do_list(int argc, char **argv)
3047 {
3048 int c;
3049 static char default_fields[] =
3050 "name,used,available,referenced,mountpoint";
3051 int types = ZFS_TYPE_DATASET;
3052 boolean_t types_specified = B_FALSE;
3053 char *fields = NULL;
3054 list_cbdata_t cb = { 0 };
3055 char *value;
3056 int limit = 0;
3057 int ret = 0;
3058 zfs_sort_column_t *sortcol = NULL;
3059 int flags = ZFS_ITER_PROP_LISTSNAPS | ZFS_ITER_ARGS_CAN_BE_PATHS;
3060
3061 /* check options */
3062 while ((c = getopt(argc, argv, "HS:d:o:prs:t:")) != -1) {
3063 switch (c) {
3064 case 'o':
3065 fields = optarg;
3066 break;
3067 case 'p':
3068 cb.cb_literal = B_TRUE;
3069 flags |= ZFS_ITER_LITERAL_PROPS;
3070 break;
3071 case 'd':
3072 limit = parse_depth(optarg, &flags);
3073 break;
3074 case 'r':
3075 flags |= ZFS_ITER_RECURSE;
3076 break;
3077 case 'H':
3078 cb.cb_scripted = B_TRUE;
3079 break;
3080 case 's':
3081 if (zfs_add_sort_column(&sortcol, optarg,
3082 B_FALSE) != 0) {
3083 (void) fprintf(stderr,
3084 gettext("invalid property '%s'\n"), optarg);
3085 usage(B_FALSE);
3086 }
3087 break;
3088 case 'S':
3089 if (zfs_add_sort_column(&sortcol, optarg,
3090 B_TRUE) != 0) {
3091 (void) fprintf(stderr,
3092 gettext("invalid property '%s'\n"), optarg);
3093 usage(B_FALSE);
3094 }
3095 break;
3096 case 't':
3097 types = 0;
3098 types_specified = B_TRUE;
3099 flags &= ~ZFS_ITER_PROP_LISTSNAPS;
3100 while (*optarg != '\0') {
3101 static char *type_subopts[] = { "filesystem",
3102 "volume", "snapshot", "snap", "bookmark",
3103 "all", NULL };
3104
3105 switch (getsubopt(&optarg, type_subopts,
3106 &value)) {
3107 case 0:
3108 types |= ZFS_TYPE_FILESYSTEM;
3109 break;
3110 case 1:
3111 types |= ZFS_TYPE_VOLUME;
3112 break;
3113 case 2:
3114 case 3:
3115 types |= ZFS_TYPE_SNAPSHOT;
3116 break;
3117 case 4:
3118 types |= ZFS_TYPE_BOOKMARK;
3119 break;
3120 case 5:
3121 types = ZFS_TYPE_DATASET |
3122 ZFS_TYPE_BOOKMARK;
3123 break;
3124 default:
3125 (void) fprintf(stderr,
3126 gettext("invalid type '%s'\n"),
3127 value);
3128 usage(B_FALSE);
3129 }
3130 }
3131 break;
3132 case ':':
3133 (void) fprintf(stderr, gettext("missing argument for "
3134 "'%c' option\n"), optopt);
3135 usage(B_FALSE);
3136 break;
3137 case '?':
3138 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3139 optopt);
3140 usage(B_FALSE);
3141 }
3142 }
3143
3144 argc -= optind;
3145 argv += optind;
3146
3147 if (fields == NULL)
3148 fields = default_fields;
3149
3150 /*
3151 * If we are only going to list snapshot names and sort by name,
3152 * then we can use faster version.
3153 */
3154 if (strcmp(fields, "name") == 0 && zfs_sort_only_by_name(sortcol))
3155 flags |= ZFS_ITER_SIMPLE;
3156
3157 /*
3158 * If "-o space" and no types were specified, don't display snapshots.
3159 */
3160 if (strcmp(fields, "space") == 0 && types_specified == B_FALSE)
3161 types &= ~ZFS_TYPE_SNAPSHOT;
3162
3163 /*
3164 * If the user specifies '-o all', the zprop_get_list() doesn't
3165 * normally include the name of the dataset. For 'zfs list', we always
3166 * want this property to be first.
3167 */
3168 if (zprop_get_list(g_zfs, fields, &cb.cb_proplist, ZFS_TYPE_DATASET)
3169 != 0)
3170 usage(B_FALSE);
3171
3172 cb.cb_first = B_TRUE;
3173
3174 ret = zfs_for_each(argc, argv, flags, types, sortcol, &cb.cb_proplist,
3175 limit, list_callback, &cb);
3176
3177 zprop_free_list(cb.cb_proplist);
3178 zfs_free_sort_columns(sortcol);
3179
3180 if (ret == 0 && cb.cb_first && !cb.cb_scripted)
3181 (void) fprintf(stderr, gettext("no datasets available\n"));
3182
3183 return (ret);
3184 }
3185
3186 /*
3187 * zfs rename [-f] <fs | snap | vol> <fs | snap | vol>
3188 * zfs rename [-f] -p <fs | vol> <fs | vol>
3189 * zfs rename -r <snap> <snap>
3190 *
3191 * Renames the given dataset to another of the same type.
3192 *
3193 * The '-p' flag creates all the non-existing ancestors of the target first.
3194 */
3195 /* ARGSUSED */
3196 static int
3197 zfs_do_rename(int argc, char **argv)
3198 {
3199 zfs_handle_t *zhp;
3200 int c;
3201 int ret = 0;
3202 boolean_t recurse = B_FALSE;
3203 boolean_t parents = B_FALSE;
3204 boolean_t force_unmount = B_FALSE;
3205
3206 /* check options */
3207 while ((c = getopt(argc, argv, "prf")) != -1) {
3208 switch (c) {
3209 case 'p':
3210 parents = B_TRUE;
3211 break;
3212 case 'r':
3213 recurse = B_TRUE;
3214 break;
3215 case 'f':
3216 force_unmount = B_TRUE;
3217 break;
3218 case '?':
3219 default:
3220 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3221 optopt);
3222 usage(B_FALSE);
3223 }
3224 }
3225
3226 argc -= optind;
3227 argv += optind;
3228
3229 /* check number of arguments */
3230 if (argc < 1) {
3231 (void) fprintf(stderr, gettext("missing source dataset "
3232 "argument\n"));
3233 usage(B_FALSE);
3234 }
3235 if (argc < 2) {
3236 (void) fprintf(stderr, gettext("missing target dataset "
3237 "argument\n"));
3238 usage(B_FALSE);
3239 }
3240 if (argc > 2) {
3241 (void) fprintf(stderr, gettext("too many arguments\n"));
3242 usage(B_FALSE);
3243 }
3244
3245 if (recurse && parents) {
3246 (void) fprintf(stderr, gettext("-p and -r options are mutually "
3247 "exclusive\n"));
3248 usage(B_FALSE);
3249 }
3250
3251 if (recurse && strchr(argv[0], '@') == 0) {
3252 (void) fprintf(stderr, gettext("source dataset for recursive "
3253 "rename must be a snapshot\n"));
3254 usage(B_FALSE);
3255 }
3256
3257 if ((zhp = zfs_open(g_zfs, argv[0], parents ? ZFS_TYPE_FILESYSTEM |
3258 ZFS_TYPE_VOLUME : ZFS_TYPE_DATASET)) == NULL)
3259 return (1);
3260
3261 /* If we were asked and the name looks good, try to create ancestors. */
3262 if (parents && zfs_name_valid(argv[1], zfs_get_type(zhp)) &&
3263 zfs_create_ancestors(g_zfs, argv[1]) != 0) {
3264 zfs_close(zhp);
3265 return (1);
3266 }
3267
3268 ret = (zfs_rename(zhp, argv[1], recurse, force_unmount) != 0);
3269
3270 zfs_close(zhp);
3271 return (ret);
3272 }
3273
3274 /*
3275 * zfs promote <fs>
3276 *
3277 * Promotes the given clone fs to be the parent
3278 */
3279 /* ARGSUSED */
3280 static int
3281 zfs_do_promote(int argc, char **argv)
3282 {
3283 zfs_handle_t *zhp;
3284 int ret = 0;
3285
3286 /* check options */
3287 if (argc > 1 && argv[1][0] == '-') {
3288 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3289 argv[1][1]);
3290 usage(B_FALSE);
3291 }
3292
3293 /* check number of arguments */
3294 if (argc < 2) {
3295 (void) fprintf(stderr, gettext("missing clone filesystem"
3296 " argument\n"));
3297 usage(B_FALSE);
3298 }
3299 if (argc > 2) {
3300 (void) fprintf(stderr, gettext("too many arguments\n"));
3301 usage(B_FALSE);
3302 }
3303
3304 zhp = zfs_open(g_zfs, argv[1], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3305 if (zhp == NULL)
3306 return (1);
3307
3308 ret = (zfs_promote(zhp) != 0);
3309
3310
3311 zfs_close(zhp);
3312 return (ret);
3313 }
3314
3315 /*
3316 * zfs rollback [-rRf] <snapshot>
3317 *
3318 * -r Delete any intervening snapshots before doing rollback
3319 * -R Delete any snapshots and their clones
3320 * -f ignored for backwards compatability
3321 *
3322 * Given a filesystem, rollback to a specific snapshot, discarding any changes
3323 * since then and making it the active dataset. If more recent snapshots exist,
3324 * the command will complain unless the '-r' flag is given.
3325 */
3326 typedef struct rollback_cbdata {
3327 uint64_t cb_create;
3328 boolean_t cb_first;
3329 int cb_doclones;
3330 char *cb_target;
3331 int cb_error;
3332 boolean_t cb_recurse;
3333 } rollback_cbdata_t;
3334
3335 static int
3336 rollback_check_dependent(zfs_handle_t *zhp, void *data)
3337 {
3338 rollback_cbdata_t *cbp = data;
3339
3340 if (cbp->cb_first && cbp->cb_recurse) {
3341 (void) fprintf(stderr, gettext("cannot rollback to "
3342 "'%s': clones of previous snapshots exist\n"),
3343 cbp->cb_target);
3344 (void) fprintf(stderr, gettext("use '-R' to "
3345 "force deletion of the following clones and "
3346 "dependents:\n"));
3347 cbp->cb_first = 0;
3348 cbp->cb_error = 1;
3349 }
3350
3351 (void) fprintf(stderr, "%s\n", zfs_get_name(zhp));
3352
3353 zfs_close(zhp);
3354 return (0);
3355 }
3356
3357
3358 /*
3359 * Report any snapshots more recent than the one specified. Used when '-r' is
3360 * not specified. We reuse this same callback for the snapshot dependents - if
3361 * 'cb_dependent' is set, then this is a dependent and we should report it
3362 * without checking the transaction group.
3363 */
3364 static int
3365 rollback_check(zfs_handle_t *zhp, void *data)
3366 {
3367 rollback_cbdata_t *cbp = data;
3368
3369 if (cbp->cb_doclones) {
3370 zfs_close(zhp);
3371 return (0);
3372 }
3373
3374 if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
3375 if (cbp->cb_first && !cbp->cb_recurse) {
3376 (void) fprintf(stderr, gettext("cannot "
3377 "rollback to '%s': more recent snapshots "
3378 "or bookmarks exist\n"),
3379 cbp->cb_target);
3380 (void) fprintf(stderr, gettext("use '-r' to "
3381 "force deletion of the following "
3382 "snapshots and bookmarks:\n"));
3383 cbp->cb_first = 0;
3384 cbp->cb_error = 1;
3385 }
3386
3387 if (cbp->cb_recurse) {
3388 if (zfs_iter_dependents(zhp, B_TRUE,
3389 rollback_check_dependent, cbp) != 0) {
3390 zfs_close(zhp);
3391 return (-1);
3392 }
3393 } else {
3394 (void) fprintf(stderr, "%s\n",
3395 zfs_get_name(zhp));
3396 }
3397 }
3398 zfs_close(zhp);
3399 return (0);
3400 }
3401
3402 static int
3403 zfs_do_rollback(int argc, char **argv)
3404 {
3405 int ret = 0;
3406 int c;
3407 boolean_t force = B_FALSE;
3408 rollback_cbdata_t cb = { 0 };
3409 zfs_handle_t *zhp, *snap;
3410 char parentname[ZFS_MAXNAMELEN];
3411 char *delim;
3412
3413 /* check options */
3414 while ((c = getopt(argc, argv, "rRf")) != -1) {
3415 switch (c) {
3416 case 'r':
3417 cb.cb_recurse = 1;
3418 break;
3419 case 'R':
3420 cb.cb_recurse = 1;
3421 cb.cb_doclones = 1;
3422 break;
3423 case 'f':
3424 force = B_TRUE;
3425 break;
3426 case '?':
3427 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3428 optopt);
3429 usage(B_FALSE);
3430 }
3431 }
3432
3433 argc -= optind;
3434 argv += optind;
3435
3436 /* check number of arguments */
3437 if (argc < 1) {
3438 (void) fprintf(stderr, gettext("missing dataset argument\n"));
3439 usage(B_FALSE);
3440 }
3441 if (argc > 1) {
3442 (void) fprintf(stderr, gettext("too many arguments\n"));
3443 usage(B_FALSE);
3444 }
3445
3446 /* open the snapshot */
3447 if ((snap = zfs_open(g_zfs, argv[0], ZFS_TYPE_SNAPSHOT)) == NULL)
3448 return (1);
3449
3450 /* open the parent dataset */
3451 (void) strlcpy(parentname, argv[0], sizeof (parentname));
3452 verify((delim = strrchr(parentname, '@')) != NULL);
3453 *delim = '\0';
3454 if ((zhp = zfs_open(g_zfs, parentname, ZFS_TYPE_DATASET)) == NULL) {
3455 zfs_close(snap);
3456 return (1);
3457 }
3458
3459 /*
3460 * Check for more recent snapshots and/or clones based on the presence
3461 * of '-r' and '-R'.
3462 */
3463 cb.cb_target = argv[0];
3464 cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
3465 cb.cb_first = B_TRUE;
3466 cb.cb_error = 0;
3467 if ((ret = zfs_iter_snapshots(zhp, B_FALSE, rollback_check, &cb)) != 0)
3468 goto out;
3469 if ((ret = zfs_iter_bookmarks(zhp, rollback_check, &cb)) != 0)
3470 goto out;
3471
3472 if ((ret = cb.cb_error) != 0)
3473 goto out;
3474
3475 /*
3476 * Rollback parent to the given snapshot.
3477 */
3478 ret = zfs_rollback(zhp, snap, force);
3479
3480 out:
3481 zfs_close(snap);
3482 zfs_close(zhp);
3483
3484 if (ret == 0)
3485 return (0);
3486 else
3487 return (1);
3488 }
3489
3490 /*
3491 * zfs set property=value ... { fs | snap | vol } ...
3492 *
3493 * Sets the given properties for all datasets specified on the command line.
3494 */
3495
3496 static int
3497 set_callback(zfs_handle_t *zhp, void *data)
3498 {
3499 nvlist_t *props = data;
3500
3501 if (zfs_prop_set_list(zhp, props) != 0) {
3502 switch (libzfs_errno(g_zfs)) {
3503 case EZFS_MOUNTFAILED:
3504 (void) fprintf(stderr, gettext("property may be set "
3505 "but unable to remount filesystem\n"));
3506 break;
3507 case EZFS_SHARENFSFAILED:
3508 (void) fprintf(stderr, gettext("property may be set "
3509 "but unable to reshare filesystem\n"));
3510 break;
3511 }
3512 return (1);
3513 }
3514 return (0);
3515 }
3516
3517 static int
3518 zfs_do_set(int argc, char **argv)
3519 {
3520 nvlist_t *props = NULL;
3521 int ds_start = -1; /* argv idx of first dataset arg */
3522 int ret = 0;
3523 int i;
3524
3525 /* check for options */
3526 if (argc > 1 && argv[1][0] == '-') {
3527 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3528 argv[1][1]);
3529 usage(B_FALSE);
3530 }
3531
3532 /* check number of arguments */
3533 if (argc < 2) {
3534 (void) fprintf(stderr, gettext("missing arguments\n"));
3535 usage(B_FALSE);
3536 }
3537 if (argc < 3) {
3538 if (strchr(argv[1], '=') == NULL) {
3539 (void) fprintf(stderr, gettext("missing property=value "
3540 "argument(s)\n"));
3541 } else {
3542 (void) fprintf(stderr, gettext("missing dataset "
3543 "name(s)\n"));
3544 }
3545 usage(B_FALSE);
3546 }
3547
3548 /* validate argument order: prop=val args followed by dataset args */
3549 for (i = 1; i < argc; i++) {
3550 if (strchr(argv[i], '=') != NULL) {
3551 if (ds_start > 0) {
3552 /* out-of-order prop=val argument */
3553 (void) fprintf(stderr, gettext("invalid "
3554 "argument order\n"));
3555 usage(B_FALSE);
3556 }
3557 } else if (ds_start < 0) {
3558 ds_start = i;
3559 }
3560 }
3561 if (ds_start < 0) {
3562 (void) fprintf(stderr, gettext("missing dataset name(s)\n"));
3563 usage(B_FALSE);
3564 }
3565
3566 /* Populate a list of property settings */
3567 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3568 nomem();
3569 for (i = 1; i < ds_start; i++) {
3570 if ((ret = parseprop(props, argv[i])) != 0)
3571 goto error;
3572 }
3573
3574 ret = zfs_for_each(argc - ds_start, argv + ds_start, 0,
3575 ZFS_TYPE_DATASET, NULL, NULL, 0, set_callback, props);
3576
3577 error:
3578 nvlist_free(props);
3579 return (ret);
3580 }
3581
3582 typedef struct snap_cbdata {
3583 nvlist_t *sd_nvl;
3584 boolean_t sd_recursive;
3585 const char *sd_snapname;
3586 } snap_cbdata_t;
3587
3588 static int
3589 zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
3590 {
3591 snap_cbdata_t *sd = arg;
3592 char *name;
3593 int rv = 0;
3594 int error;
3595
3596 if (sd->sd_recursive &&
3597 zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) != 0) {
3598 zfs_close(zhp);
3599 return (0);
3600 }
3601
3602 error = asprintf(&name, "%s@%s", zfs_get_name(zhp), sd->sd_snapname);
3603 if (error == -1)
3604 nomem();
3605 fnvlist_add_boolean(sd->sd_nvl, name);
3606 free(name);
3607
3608 if (sd->sd_recursive)
3609 rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
3610 zfs_close(zhp);
3611 return (rv);
3612 }
3613
3614 /*
3615 * zfs snapshot [-r] [-o prop=value] ... <fs@snap>
3616 *
3617 * Creates a snapshot with the given name. While functionally equivalent to
3618 * 'zfs create', it is a separate command to differentiate intent.
3619 */
3620 static int
3621 zfs_do_snapshot(int argc, char **argv)
3622 {
3623 int ret = 0;
3624 signed char c;
3625 nvlist_t *props;
3626 snap_cbdata_t sd = { 0 };
3627 boolean_t multiple_snaps = B_FALSE;
3628
3629 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3630 nomem();
3631 if (nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) != 0)
3632 nomem();
3633
3634 /* check options */
3635 while ((c = getopt(argc, argv, "ro:")) != -1) {
3636 switch (c) {
3637 case 'o':
3638 if (parseprop(props, optarg) != 0)
3639 return (1);
3640 break;
3641 case 'r':
3642 sd.sd_recursive = B_TRUE;
3643 multiple_snaps = B_TRUE;
3644 break;
3645 case '?':
3646 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3647 optopt);
3648 goto usage;
3649 }
3650 }
3651
3652 argc -= optind;
3653 argv += optind;
3654
3655 /* check number of arguments */
3656 if (argc < 1) {
3657 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3658 goto usage;
3659 }
3660
3661 if (argc > 1)
3662 multiple_snaps = B_TRUE;
3663 for (; argc > 0; argc--, argv++) {
3664 char *atp;
3665 zfs_handle_t *zhp;
3666
3667 atp = strchr(argv[0], '@');
3668 if (atp == NULL)
3669 goto usage;
3670 *atp = '\0';
3671 sd.sd_snapname = atp + 1;
3672 zhp = zfs_open(g_zfs, argv[0],
3673 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3674 if (zhp == NULL)
3675 goto usage;
3676 if (zfs_snapshot_cb(zhp, &sd) != 0)
3677 goto usage;
3678 }
3679
3680 ret = zfs_snapshot_nvl(g_zfs, sd.sd_nvl, props);
3681 nvlist_free(sd.sd_nvl);
3682 nvlist_free(props);
3683 if (ret != 0 && multiple_snaps)
3684 (void) fprintf(stderr, gettext("no snapshots were created\n"));
3685 return (ret != 0);
3686
3687 usage:
3688 nvlist_free(sd.sd_nvl);
3689 nvlist_free(props);
3690 usage(B_FALSE);
3691 return (-1);
3692 }
3693
3694 /*
3695 * Send a backup stream to stdout.
3696 */
3697 static int
3698 zfs_do_send(int argc, char **argv)
3699 {
3700 char *fromname = NULL;
3701 char *toname = NULL;
3702 char *cp;
3703 zfs_handle_t *zhp;
3704 sendflags_t flags = { 0 };
3705 int c, err;
3706 nvlist_t *dbgnv = NULL;
3707 boolean_t extraverbose = B_FALSE;
3708
3709 /* check options */
3710 while ((c = getopt(argc, argv, ":i:I:RDpvnPLe")) != -1) {
3711 switch (c) {
3712 case 'i':
3713 if (fromname)
3714 usage(B_FALSE);
3715 fromname = optarg;
3716 break;
3717 case 'I':
3718 if (fromname)
3719 usage(B_FALSE);
3720 fromname = optarg;
3721 flags.doall = B_TRUE;
3722 break;
3723 case 'R':
3724 flags.replicate = B_TRUE;
3725 break;
3726 case 'p':
3727 flags.props = B_TRUE;
3728 break;
3729 case 'P':
3730 flags.parsable = B_TRUE;
3731 flags.verbose = B_TRUE;
3732 break;
3733 case 'v':
3734 if (flags.verbose)
3735 extraverbose = B_TRUE;
3736 flags.verbose = B_TRUE;
3737 flags.progress = B_TRUE;
3738 break;
3739 case 'D':
3740 flags.dedup = B_TRUE;
3741 break;
3742 case 'n':
3743 flags.dryrun = B_TRUE;
3744 break;
3745 case 'L':
3746 flags.largeblock = B_TRUE;
3747 break;
3748 case 'e':
3749 flags.embed_data = B_TRUE;
3750 break;
3751 case ':':
3752 (void) fprintf(stderr, gettext("missing argument for "
3753 "'%c' option\n"), optopt);
3754 usage(B_FALSE);
3755 break;
3756 case '?':
3757 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3758 optopt);
3759 usage(B_FALSE);
3760 }
3761 }
3762
3763 argc -= optind;
3764 argv += optind;
3765
3766 /* check number of arguments */
3767 if (argc < 1) {
3768 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3769 usage(B_FALSE);
3770 }
3771 if (argc > 1) {
3772 (void) fprintf(stderr, gettext("too many arguments\n"));
3773 usage(B_FALSE);
3774 }
3775
3776 if (!flags.dryrun && isatty(STDOUT_FILENO)) {
3777 (void) fprintf(stderr,
3778 gettext("Error: Stream can not be written to a terminal.\n"
3779 "You must redirect standard output.\n"));
3780 return (1);
3781 }
3782
3783 /*
3784 * Special case sending a filesystem, or from a bookmark.
3785 */
3786 if (strchr(argv[0], '@') == NULL ||
3787 (fromname && strchr(fromname, '#') != NULL)) {
3788 char frombuf[ZFS_MAXNAMELEN];
3789 enum lzc_send_flags lzc_flags = 0;
3790
3791 if (flags.replicate || flags.doall || flags.props ||
3792 flags.dedup || flags.dryrun || flags.verbose ||
3793 flags.progress) {
3794 (void) fprintf(stderr,
3795 gettext("Error: "
3796 "Unsupported flag with filesystem or bookmark.\n"));
3797 return (1);
3798 }
3799
3800 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_DATASET);
3801 if (zhp == NULL)
3802 return (1);
3803
3804 if (flags.largeblock)
3805 lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
3806 if (flags.embed_data)
3807 lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
3808
3809 if (fromname != NULL &&
3810 (fromname[0] == '#' || fromname[0] == '@')) {
3811 /*
3812 * Incremental source name begins with # or @.
3813 * Default to same fs as target.
3814 */
3815 (void) strncpy(frombuf, argv[0], sizeof (frombuf));
3816 cp = strchr(frombuf, '@');
3817 if (cp != NULL)
3818 *cp = '\0';
3819 (void) strlcat(frombuf, fromname, sizeof (frombuf));
3820 fromname = frombuf;
3821 }
3822 err = zfs_send_one(zhp, fromname, STDOUT_FILENO, lzc_flags);
3823 zfs_close(zhp);
3824 return (err != 0);
3825 }
3826
3827 cp = strchr(argv[0], '@');
3828 *cp = '\0';
3829 toname = cp + 1;
3830 zhp = zfs_open(g_zfs, argv[0], ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3831 if (zhp == NULL)
3832 return (1);
3833
3834 /*
3835 * If they specified the full path to the snapshot, chop off
3836 * everything except the short name of the snapshot, but special
3837 * case if they specify the origin.
3838 */
3839 if (fromname && (cp = strchr(fromname, '@')) != NULL) {
3840 char origin[ZFS_MAXNAMELEN];
3841 zprop_source_t src;
3842
3843 (void) zfs_prop_get(zhp, ZFS_PROP_ORIGIN,
3844 origin, sizeof (origin), &src, NULL, 0, B_FALSE);
3845
3846 if (strcmp(origin, fromname) == 0) {
3847 fromname = NULL;
3848 flags.fromorigin = B_TRUE;
3849 } else {
3850 *cp = '\0';
3851 if (cp != fromname && strcmp(argv[0], fromname)) {
3852 (void) fprintf(stderr,
3853 gettext("incremental source must be "
3854 "in same filesystem\n"));
3855 usage(B_FALSE);
3856 }
3857 fromname = cp + 1;
3858 if (strchr(fromname, '@') || strchr(fromname, '/')) {
3859 (void) fprintf(stderr,
3860 gettext("invalid incremental source\n"));
3861 usage(B_FALSE);
3862 }
3863 }
3864 }
3865
3866 if (flags.replicate && fromname == NULL)
3867 flags.doall = B_TRUE;
3868
3869 err = zfs_send(zhp, fromname, toname, &flags, STDOUT_FILENO, NULL, 0,
3870 extraverbose ? &dbgnv : NULL);
3871
3872 if (extraverbose && dbgnv != NULL) {
3873 /*
3874 * dump_nvlist prints to stdout, but that's been
3875 * redirected to a file. Make it print to stderr
3876 * instead.
3877 */
3878 (void) dup2(STDERR_FILENO, STDOUT_FILENO);
3879 dump_nvlist(dbgnv, 0);
3880 nvlist_free(dbgnv);
3881 }
3882 zfs_close(zhp);
3883
3884 return (err != 0);
3885 }
3886
3887 /*
3888 * zfs receive [-vnFu] [-d | -e] <fs@snap>
3889 *
3890 * Restore a backup stream from stdin.
3891 */
3892 static int
3893 zfs_do_receive(int argc, char **argv)
3894 {
3895 int c, err;
3896 recvflags_t flags = { 0 };
3897 nvlist_t *props;
3898 nvpair_t *nvp = NULL;
3899
3900 if (nvlist_alloc(&props, NV_UNIQUE_NAME, 0) != 0)
3901 nomem();
3902
3903 /* check options */
3904 while ((c = getopt(argc, argv, ":o:denuvF")) != -1) {
3905 switch (c) {
3906 case 'o':
3907 if (parseprop(props, optarg) != 0)
3908 return (1);
3909 break;
3910 case 'd':
3911 flags.isprefix = B_TRUE;
3912 break;
3913 case 'e':
3914 flags.isprefix = B_TRUE;
3915 flags.istail = B_TRUE;
3916 break;
3917 case 'n':
3918 flags.dryrun = B_TRUE;
3919 break;
3920 case 'u':
3921 flags.nomount = B_TRUE;
3922 break;
3923 case 'v':
3924 flags.verbose = B_TRUE;
3925 break;
3926 case 'F':
3927 flags.force = B_TRUE;
3928 break;
3929 case ':':
3930 (void) fprintf(stderr, gettext("missing argument for "
3931 "'%c' option\n"), optopt);
3932 usage(B_FALSE);
3933 break;
3934 case '?':
3935 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
3936 optopt);
3937 usage(B_FALSE);
3938 }
3939 }
3940
3941 argc -= optind;
3942 argv += optind;
3943
3944 /* check number of arguments */
3945 if (argc < 1) {
3946 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
3947 usage(B_FALSE);
3948 }
3949 if (argc > 1) {
3950 (void) fprintf(stderr, gettext("too many arguments\n"));
3951 usage(B_FALSE);
3952 }
3953
3954 while ((nvp = nvlist_next_nvpair(props, nvp))) {
3955 if (strcmp(nvpair_name(nvp), "origin") != 0) {
3956 (void) fprintf(stderr, gettext("invalid option"));
3957 usage(B_FALSE);
3958 }
3959 }
3960
3961 if (isatty(STDIN_FILENO)) {
3962 (void) fprintf(stderr,
3963 gettext("Error: Backup stream can not be read "
3964 "from a terminal.\n"
3965 "You must redirect standard input.\n"));
3966 return (1);
3967 }
3968
3969 err = zfs_receive(g_zfs, argv[0], props, &flags, STDIN_FILENO, NULL);
3970
3971 return (err != 0);
3972 }
3973
3974 /*
3975 * allow/unallow stuff
3976 */
3977 /* copied from zfs/sys/dsl_deleg.h */
3978 #define ZFS_DELEG_PERM_CREATE "create"
3979 #define ZFS_DELEG_PERM_DESTROY "destroy"
3980 #define ZFS_DELEG_PERM_SNAPSHOT "snapshot"
3981 #define ZFS_DELEG_PERM_ROLLBACK "rollback"
3982 #define ZFS_DELEG_PERM_CLONE "clone"
3983 #define ZFS_DELEG_PERM_PROMOTE "promote"
3984 #define ZFS_DELEG_PERM_RENAME "rename"
3985 #define ZFS_DELEG_PERM_MOUNT "mount"
3986 #define ZFS_DELEG_PERM_SHARE "share"
3987 #define ZFS_DELEG_PERM_SEND "send"
3988 #define ZFS_DELEG_PERM_RECEIVE "receive"
3989 #define ZFS_DELEG_PERM_ALLOW "allow"
3990 #define ZFS_DELEG_PERM_USERPROP "userprop"
3991 #define ZFS_DELEG_PERM_VSCAN "vscan" /* ??? */
3992 #define ZFS_DELEG_PERM_USERQUOTA "userquota"
3993 #define ZFS_DELEG_PERM_GROUPQUOTA "groupquota"
3994 #define ZFS_DELEG_PERM_USERUSED "userused"
3995 #define ZFS_DELEG_PERM_GROUPUSED "groupused"
3996 #define ZFS_DELEG_PERM_HOLD "hold"
3997 #define ZFS_DELEG_PERM_RELEASE "release"
3998 #define ZFS_DELEG_PERM_DIFF "diff"
3999 #define ZFS_DELEG_PERM_BOOKMARK "bookmark"
4000
4001 #define ZFS_NUM_DELEG_NOTES ZFS_DELEG_NOTE_NONE
4002
4003 static zfs_deleg_perm_tab_t zfs_deleg_perm_tbl[] = {
4004 { ZFS_DELEG_PERM_ALLOW, ZFS_DELEG_NOTE_ALLOW },
4005 { ZFS_DELEG_PERM_CLONE, ZFS_DELEG_NOTE_CLONE },
4006 { ZFS_DELEG_PERM_CREATE, ZFS_DELEG_NOTE_CREATE },
4007 { ZFS_DELEG_PERM_DESTROY, ZFS_DELEG_NOTE_DESTROY },
4008 { ZFS_DELEG_PERM_DIFF, ZFS_DELEG_NOTE_DIFF},
4009 { ZFS_DELEG_PERM_HOLD, ZFS_DELEG_NOTE_HOLD },
4010 { ZFS_DELEG_PERM_MOUNT, ZFS_DELEG_NOTE_MOUNT },
4011 { ZFS_DELEG_PERM_PROMOTE, ZFS_DELEG_NOTE_PROMOTE },
4012 { ZFS_DELEG_PERM_RECEIVE, ZFS_DELEG_NOTE_RECEIVE },
4013 { ZFS_DELEG_PERM_RELEASE, ZFS_DELEG_NOTE_RELEASE },
4014 { ZFS_DELEG_PERM_RENAME, ZFS_DELEG_NOTE_RENAME },
4015 { ZFS_DELEG_PERM_ROLLBACK, ZFS_DELEG_NOTE_ROLLBACK },
4016 { ZFS_DELEG_PERM_SEND, ZFS_DELEG_NOTE_SEND },
4017 { ZFS_DELEG_PERM_SHARE, ZFS_DELEG_NOTE_SHARE },
4018 { ZFS_DELEG_PERM_SNAPSHOT, ZFS_DELEG_NOTE_SNAPSHOT },
4019 { ZFS_DELEG_PERM_BOOKMARK, ZFS_DELEG_NOTE_BOOKMARK },
4020
4021 { ZFS_DELEG_PERM_GROUPQUOTA, ZFS_DELEG_NOTE_GROUPQUOTA },
4022 { ZFS_DELEG_PERM_GROUPUSED, ZFS_DELEG_NOTE_GROUPUSED },
4023 { ZFS_DELEG_PERM_USERPROP, ZFS_DELEG_NOTE_USERPROP },
4024 { ZFS_DELEG_PERM_USERQUOTA, ZFS_DELEG_NOTE_USERQUOTA },
4025 { ZFS_DELEG_PERM_USERUSED, ZFS_DELEG_NOTE_USERUSED },
4026 { NULL, ZFS_DELEG_NOTE_NONE }
4027 };
4028
4029 /* permission structure */
4030 typedef struct deleg_perm {
4031 zfs_deleg_who_type_t dp_who_type;
4032 const char *dp_name;
4033 boolean_t dp_local;
4034 boolean_t dp_descend;
4035 } deleg_perm_t;
4036
4037 /* */
4038 typedef struct deleg_perm_node {
4039 deleg_perm_t dpn_perm;
4040
4041 uu_avl_node_t dpn_avl_node;
4042 } deleg_perm_node_t;
4043
4044 typedef struct fs_perm fs_perm_t;
4045
4046 /* permissions set */
4047 typedef struct who_perm {
4048 zfs_deleg_who_type_t who_type;
4049 const char *who_name; /* id */
4050 char who_ug_name[256]; /* user/group name */
4051 fs_perm_t *who_fsperm; /* uplink */
4052
4053 uu_avl_t *who_deleg_perm_avl; /* permissions */
4054 } who_perm_t;
4055
4056 /* */
4057 typedef struct who_perm_node {
4058 who_perm_t who_perm;
4059 uu_avl_node_t who_avl_node;
4060 } who_perm_node_t;
4061
4062 typedef struct fs_perm_set fs_perm_set_t;
4063 /* fs permissions */
4064 struct fs_perm {
4065 const char *fsp_name;
4066
4067 uu_avl_t *fsp_sc_avl; /* sets,create */
4068 uu_avl_t *fsp_uge_avl; /* user,group,everyone */
4069
4070 fs_perm_set_t *fsp_set; /* uplink */
4071 };
4072
4073 /* */
4074 typedef struct fs_perm_node {
4075 fs_perm_t fspn_fsperm;
4076 uu_avl_t *fspn_avl;
4077
4078 uu_list_node_t fspn_list_node;
4079 } fs_perm_node_t;
4080
4081 /* top level structure */
4082 struct fs_perm_set {
4083 uu_list_pool_t *fsps_list_pool;
4084 uu_list_t *fsps_list; /* list of fs_perms */
4085
4086 uu_avl_pool_t *fsps_named_set_avl_pool;
4087 uu_avl_pool_t *fsps_who_perm_avl_pool;
4088 uu_avl_pool_t *fsps_deleg_perm_avl_pool;
4089 };
4090
4091 static inline const char *
4092 deleg_perm_type(zfs_deleg_note_t note)
4093 {
4094 /* subcommands */
4095 switch (note) {
4096 /* SUBCOMMANDS */
4097 /* OTHER */
4098 case ZFS_DELEG_NOTE_GROUPQUOTA:
4099 case ZFS_DELEG_NOTE_GROUPUSED:
4100 case ZFS_DELEG_NOTE_USERPROP:
4101 case ZFS_DELEG_NOTE_USERQUOTA:
4102 case ZFS_DELEG_NOTE_USERUSED:
4103 /* other */
4104 return (gettext("other"));
4105 default:
4106 return (gettext("subcommand"));
4107 }
4108 }
4109
4110 static int inline
4111 who_type2weight(zfs_deleg_who_type_t who_type)
4112 {
4113 int res;
4114 switch (who_type) {
4115 case ZFS_DELEG_NAMED_SET_SETS:
4116 case ZFS_DELEG_NAMED_SET:
4117 res = 0;
4118 break;
4119 case ZFS_DELEG_CREATE_SETS:
4120 case ZFS_DELEG_CREATE:
4121 res = 1;
4122 break;
4123 case ZFS_DELEG_USER_SETS:
4124 case ZFS_DELEG_USER:
4125 res = 2;
4126 break;
4127 case ZFS_DELEG_GROUP_SETS:
4128 case ZFS_DELEG_GROUP:
4129 res = 3;
4130 break;
4131 case ZFS_DELEG_EVERYONE_SETS:
4132 case ZFS_DELEG_EVERYONE:
4133 res = 4;
4134 break;
4135 default:
4136 res = -1;
4137 }
4138
4139 return (res);
4140 }
4141
4142 /* ARGSUSED */
4143 static int
4144 who_perm_compare(const void *larg, const void *rarg, void *unused)
4145 {
4146 const who_perm_node_t *l = larg;
4147 const who_perm_node_t *r = rarg;
4148 zfs_deleg_who_type_t ltype = l->who_perm.who_type;
4149 zfs_deleg_who_type_t rtype = r->who_perm.who_type;
4150 int lweight = who_type2weight(ltype);
4151 int rweight = who_type2weight(rtype);
4152 int res = lweight - rweight;
4153 if (res == 0)
4154 res = strncmp(l->who_perm.who_name, r->who_perm.who_name,
4155 ZFS_MAX_DELEG_NAME-1);
4156
4157 if (res == 0)
4158 return (0);
4159 if (res > 0)
4160 return (1);
4161 else
4162 return (-1);
4163 }
4164
4165 /* ARGSUSED */
4166 static int
4167 deleg_perm_compare(const void *larg, const void *rarg, void *unused)
4168 {
4169 const deleg_perm_node_t *l = larg;
4170 const deleg_perm_node_t *r = rarg;
4171 int res = strncmp(l->dpn_perm.dp_name, r->dpn_perm.dp_name,
4172 ZFS_MAX_DELEG_NAME-1);
4173
4174 if (res == 0)
4175 return (0);
4176
4177 if (res > 0)
4178 return (1);
4179 else
4180 return (-1);
4181 }
4182
4183 static inline void
4184 fs_perm_set_init(fs_perm_set_t *fspset)
4185 {
4186 bzero(fspset, sizeof (fs_perm_set_t));
4187
4188 if ((fspset->fsps_list_pool = uu_list_pool_create("fsps_list_pool",
4189 sizeof (fs_perm_node_t), offsetof(fs_perm_node_t, fspn_list_node),
4190 NULL, UU_DEFAULT)) == NULL)
4191 nomem();
4192 if ((fspset->fsps_list = uu_list_create(fspset->fsps_list_pool, NULL,
4193 UU_DEFAULT)) == NULL)
4194 nomem();
4195
4196 if ((fspset->fsps_named_set_avl_pool = uu_avl_pool_create(
4197 "named_set_avl_pool", sizeof (who_perm_node_t), offsetof(
4198 who_perm_node_t, who_avl_node), who_perm_compare,
4199 UU_DEFAULT)) == NULL)
4200 nomem();
4201
4202 if ((fspset->fsps_who_perm_avl_pool = uu_avl_pool_create(
4203 "who_perm_avl_pool", sizeof (who_perm_node_t), offsetof(
4204 who_perm_node_t, who_avl_node), who_perm_compare,
4205 UU_DEFAULT)) == NULL)
4206 nomem();
4207
4208 if ((fspset->fsps_deleg_perm_avl_pool = uu_avl_pool_create(
4209 "deleg_perm_avl_pool", sizeof (deleg_perm_node_t), offsetof(
4210 deleg_perm_node_t, dpn_avl_node), deleg_perm_compare, UU_DEFAULT))
4211 == NULL)
4212 nomem();
4213 }
4214
4215 static inline void fs_perm_fini(fs_perm_t *);
4216 static inline void who_perm_fini(who_perm_t *);
4217
4218 static inline void
4219 fs_perm_set_fini(fs_perm_set_t *fspset)
4220 {
4221 fs_perm_node_t *node = uu_list_first(fspset->fsps_list);
4222
4223 while (node != NULL) {
4224 fs_perm_node_t *next_node =
4225 uu_list_next(fspset->fsps_list, node);
4226 fs_perm_t *fsperm = &node->fspn_fsperm;
4227 fs_perm_fini(fsperm);
4228 uu_list_remove(fspset->fsps_list, node);
4229 free(node);
4230 node = next_node;
4231 }
4232
4233 uu_avl_pool_destroy(fspset->fsps_named_set_avl_pool);
4234 uu_avl_pool_destroy(fspset->fsps_who_perm_avl_pool);
4235 uu_avl_pool_destroy(fspset->fsps_deleg_perm_avl_pool);
4236 }
4237
4238 static inline void
4239 deleg_perm_init(deleg_perm_t *deleg_perm, zfs_deleg_who_type_t type,
4240 const char *name)
4241 {
4242 deleg_perm->dp_who_type = type;
4243 deleg_perm->dp_name = name;
4244 }
4245
4246 static inline void
4247 who_perm_init(who_perm_t *who_perm, fs_perm_t *fsperm,
4248 zfs_deleg_who_type_t type, const char *name)
4249 {
4250 uu_avl_pool_t *pool;
4251 pool = fsperm->fsp_set->fsps_deleg_perm_avl_pool;
4252
4253 bzero(who_perm, sizeof (who_perm_t));
4254
4255 if ((who_perm->who_deleg_perm_avl = uu_avl_create(pool, NULL,
4256 UU_DEFAULT)) == NULL)
4257 nomem();
4258
4259 who_perm->who_type = type;
4260 who_perm->who_name = name;
4261 who_perm->who_fsperm = fsperm;
4262 }
4263
4264 static inline void
4265 who_perm_fini(who_perm_t *who_perm)
4266 {
4267 deleg_perm_node_t *node = uu_avl_first(who_perm->who_deleg_perm_avl);
4268
4269 while (node != NULL) {
4270 deleg_perm_node_t *next_node =
4271 uu_avl_next(who_perm->who_deleg_perm_avl, node);
4272
4273 uu_avl_remove(who_perm->who_deleg_perm_avl, node);
4274 free(node);
4275 node = next_node;
4276 }
4277
4278 uu_avl_destroy(who_perm->who_deleg_perm_avl);
4279 }
4280
4281 static inline void
4282 fs_perm_init(fs_perm_t *fsperm, fs_perm_set_t *fspset, const char *fsname)
4283 {
4284 uu_avl_pool_t *nset_pool = fspset->fsps_named_set_avl_pool;
4285 uu_avl_pool_t *who_pool = fspset->fsps_who_perm_avl_pool;
4286
4287 bzero(fsperm, sizeof (fs_perm_t));
4288
4289 if ((fsperm->fsp_sc_avl = uu_avl_create(nset_pool, NULL, UU_DEFAULT))
4290 == NULL)
4291 nomem();
4292
4293 if ((fsperm->fsp_uge_avl = uu_avl_create(who_pool, NULL, UU_DEFAULT))
4294 == NULL)
4295 nomem();
4296
4297 fsperm->fsp_set = fspset;
4298 fsperm->fsp_name = fsname;
4299 }
4300
4301 static inline void
4302 fs_perm_fini(fs_perm_t *fsperm)
4303 {
4304 who_perm_node_t *node = uu_avl_first(fsperm->fsp_sc_avl);
4305 while (node != NULL) {
4306 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_sc_avl,
4307 node);
4308 who_perm_t *who_perm = &node->who_perm;
4309 who_perm_fini(who_perm);
4310 uu_avl_remove(fsperm->fsp_sc_avl, node);
4311 free(node);
4312 node = next_node;
4313 }
4314
4315 node = uu_avl_first(fsperm->fsp_uge_avl);
4316 while (node != NULL) {
4317 who_perm_node_t *next_node = uu_avl_next(fsperm->fsp_uge_avl,
4318 node);
4319 who_perm_t *who_perm = &node->who_perm;
4320 who_perm_fini(who_perm);
4321 uu_avl_remove(fsperm->fsp_uge_avl, node);
4322 free(node);
4323 node = next_node;
4324 }
4325
4326 uu_avl_destroy(fsperm->fsp_sc_avl);
4327 uu_avl_destroy(fsperm->fsp_uge_avl);
4328 }
4329
4330 static void inline
4331 set_deleg_perm_node(uu_avl_t *avl, deleg_perm_node_t *node,
4332 zfs_deleg_who_type_t who_type, const char *name, char locality)
4333 {
4334 uu_avl_index_t idx = 0;
4335
4336 deleg_perm_node_t *found_node = NULL;
4337 deleg_perm_t *deleg_perm = &node->dpn_perm;
4338
4339 deleg_perm_init(deleg_perm, who_type, name);
4340
4341 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4342 == NULL)
4343 uu_avl_insert(avl, node, idx);
4344 else {
4345 node = found_node;
4346 deleg_perm = &node->dpn_perm;
4347 }
4348
4349
4350 switch (locality) {
4351 case ZFS_DELEG_LOCAL:
4352 deleg_perm->dp_local = B_TRUE;
4353 break;
4354 case ZFS_DELEG_DESCENDENT:
4355 deleg_perm->dp_descend = B_TRUE;
4356 break;
4357 case ZFS_DELEG_NA:
4358 break;
4359 default:
4360 assert(B_FALSE); /* invalid locality */
4361 }
4362 }
4363
4364 static inline int
4365 parse_who_perm(who_perm_t *who_perm, nvlist_t *nvl, char locality)
4366 {
4367 nvpair_t *nvp = NULL;
4368 fs_perm_set_t *fspset = who_perm->who_fsperm->fsp_set;
4369 uu_avl_t *avl = who_perm->who_deleg_perm_avl;
4370 zfs_deleg_who_type_t who_type = who_perm->who_type;
4371
4372 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4373 const char *name = nvpair_name(nvp);
4374 data_type_t type = nvpair_type(nvp);
4375 uu_avl_pool_t *avl_pool = fspset->fsps_deleg_perm_avl_pool;
4376 deleg_perm_node_t *node =
4377 safe_malloc(sizeof (deleg_perm_node_t));
4378
4379 VERIFY(type == DATA_TYPE_BOOLEAN);
4380
4381 uu_avl_node_init(node, &node->dpn_avl_node, avl_pool);
4382 set_deleg_perm_node(avl, node, who_type, name, locality);
4383 }
4384
4385 return (0);
4386 }
4387
4388 static inline int
4389 parse_fs_perm(fs_perm_t *fsperm, nvlist_t *nvl)
4390 {
4391 nvpair_t *nvp = NULL;
4392 fs_perm_set_t *fspset = fsperm->fsp_set;
4393
4394 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4395 nvlist_t *nvl2 = NULL;
4396 const char *name = nvpair_name(nvp);
4397 uu_avl_t *avl = NULL;
4398 uu_avl_pool_t *avl_pool = NULL;
4399 zfs_deleg_who_type_t perm_type = name[0];
4400 char perm_locality = name[1];
4401 const char *perm_name = name + 3;
4402 boolean_t is_set = B_TRUE;
4403 who_perm_t *who_perm = NULL;
4404
4405 assert('$' == name[2]);
4406
4407 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4408 return (-1);
4409
4410 switch (perm_type) {
4411 case ZFS_DELEG_CREATE:
4412 case ZFS_DELEG_CREATE_SETS:
4413 case ZFS_DELEG_NAMED_SET:
4414 case ZFS_DELEG_NAMED_SET_SETS:
4415 avl_pool = fspset->fsps_named_set_avl_pool;
4416 avl = fsperm->fsp_sc_avl;
4417 break;
4418 case ZFS_DELEG_USER:
4419 case ZFS_DELEG_USER_SETS:
4420 case ZFS_DELEG_GROUP:
4421 case ZFS_DELEG_GROUP_SETS:
4422 case ZFS_DELEG_EVERYONE:
4423 case ZFS_DELEG_EVERYONE_SETS:
4424 avl_pool = fspset->fsps_who_perm_avl_pool;
4425 avl = fsperm->fsp_uge_avl;
4426 break;
4427 default:
4428 break;
4429 }
4430
4431 if (is_set) {
4432 who_perm_node_t *found_node = NULL;
4433 who_perm_node_t *node = safe_malloc(
4434 sizeof (who_perm_node_t));
4435 who_perm = &node->who_perm;
4436 uu_avl_index_t idx = 0;
4437
4438 uu_avl_node_init(node, &node->who_avl_node, avl_pool);
4439 who_perm_init(who_perm, fsperm, perm_type, perm_name);
4440
4441 if ((found_node = uu_avl_find(avl, node, NULL, &idx))
4442 == NULL) {
4443 if (avl == fsperm->fsp_uge_avl) {
4444 uid_t rid = 0;
4445 struct passwd *p = NULL;
4446 struct group *g = NULL;
4447 const char *nice_name = NULL;
4448
4449 switch (perm_type) {
4450 case ZFS_DELEG_USER_SETS:
4451 case ZFS_DELEG_USER:
4452 rid = atoi(perm_name);
4453 p = getpwuid(rid);
4454 if (p)
4455 nice_name = p->pw_name;
4456 break;
4457 case ZFS_DELEG_GROUP_SETS:
4458 case ZFS_DELEG_GROUP:
4459 rid = atoi(perm_name);
4460 g = getgrgid(rid);
4461 if (g)
4462 nice_name = g->gr_name;
4463 break;
4464 default:
4465 break;
4466 }
4467
4468 if (nice_name != NULL)
4469 (void) strlcpy(
4470 node->who_perm.who_ug_name,
4471 nice_name, 256);
4472 }
4473
4474 uu_avl_insert(avl, node, idx);
4475 } else {
4476 node = found_node;
4477 who_perm = &node->who_perm;
4478 }
4479 }
4480
4481 (void) parse_who_perm(who_perm, nvl2, perm_locality);
4482 }
4483
4484 return (0);
4485 }
4486
4487 static inline int
4488 parse_fs_perm_set(fs_perm_set_t *fspset, nvlist_t *nvl)
4489 {
4490 nvpair_t *nvp = NULL;
4491 uu_avl_index_t idx = 0;
4492
4493 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
4494 nvlist_t *nvl2 = NULL;
4495 const char *fsname = nvpair_name(nvp);
4496 data_type_t type = nvpair_type(nvp);
4497 fs_perm_t *fsperm = NULL;
4498 fs_perm_node_t *node = safe_malloc(sizeof (fs_perm_node_t));
4499 if (node == NULL)
4500 nomem();
4501
4502 fsperm = &node->fspn_fsperm;
4503
4504 VERIFY(DATA_TYPE_NVLIST == type);
4505
4506 uu_list_node_init(node, &node->fspn_list_node,
4507 fspset->fsps_list_pool);
4508
4509 idx = uu_list_numnodes(fspset->fsps_list);
4510 fs_perm_init(fsperm, fspset, fsname);
4511
4512 if (nvpair_value_nvlist(nvp, &nvl2) != 0)
4513 return (-1);
4514
4515 (void) parse_fs_perm(fsperm, nvl2);
4516
4517 uu_list_insert(fspset->fsps_list, node, idx);
4518 }
4519
4520 return (0);
4521 }
4522
4523 static inline const char *
4524 deleg_perm_comment(zfs_deleg_note_t note)
4525 {
4526 const char *str = "";
4527
4528 /* subcommands */
4529 switch (note) {
4530 /* SUBCOMMANDS */
4531 case ZFS_DELEG_NOTE_ALLOW:
4532 str = gettext("Must also have the permission that is being"
4533 "\n\t\t\t\tallowed");
4534 break;
4535 case ZFS_DELEG_NOTE_CLONE:
4536 str = gettext("Must also have the 'create' ability and 'mount'"
4537 "\n\t\t\t\tability in the origin file system");
4538 break;
4539 case ZFS_DELEG_NOTE_CREATE:
4540 str = gettext("Must also have the 'mount' ability");
4541 break;
4542 case ZFS_DELEG_NOTE_DESTROY:
4543 str = gettext("Must also have the 'mount' ability");
4544 break;
4545 case ZFS_DELEG_NOTE_DIFF:
4546 str = gettext("Allows lookup of paths within a dataset;"
4547 "\n\t\t\t\tgiven an object number. Ordinary users need this"
4548 "\n\t\t\t\tin order to use zfs diff");
4549 break;
4550 case ZFS_DELEG_NOTE_HOLD:
4551 str = gettext("Allows adding a user hold to a snapshot");
4552 break;
4553 case ZFS_DELEG_NOTE_MOUNT:
4554 str = gettext("Allows mount/umount of ZFS datasets");
4555 break;
4556 case ZFS_DELEG_NOTE_PROMOTE:
4557 str = gettext("Must also have the 'mount'\n\t\t\t\tand"
4558 " 'promote' ability in the origin file system");
4559 break;
4560 case ZFS_DELEG_NOTE_RECEIVE:
4561 str = gettext("Must also have the 'mount' and 'create'"
4562 " ability");
4563 break;
4564 case ZFS_DELEG_NOTE_RELEASE:
4565 str = gettext("Allows releasing a user hold which\n\t\t\t\t"
4566 "might destroy the snapshot");
4567 break;
4568 case ZFS_DELEG_NOTE_RENAME:
4569 str = gettext("Must also have the 'mount' and 'create'"
4570 "\n\t\t\t\tability in the new parent");
4571 break;
4572 case ZFS_DELEG_NOTE_ROLLBACK:
4573 str = gettext("");
4574 break;
4575 case ZFS_DELEG_NOTE_SEND:
4576 str = gettext("");
4577 break;
4578 case ZFS_DELEG_NOTE_SHARE:
4579 str = gettext("Allows sharing file systems over NFS or SMB"
4580 "\n\t\t\t\tprotocols");
4581 break;
4582 case ZFS_DELEG_NOTE_SNAPSHOT:
4583 str = gettext("");
4584 break;
4585 /*
4586 * case ZFS_DELEG_NOTE_VSCAN:
4587 * str = gettext("");
4588 * break;
4589 */
4590 /* OTHER */
4591 case ZFS_DELEG_NOTE_GROUPQUOTA:
4592 str = gettext("Allows accessing any groupquota@... property");
4593 break;
4594 case ZFS_DELEG_NOTE_GROUPUSED:
4595 str = gettext("Allows reading any groupused@... property");
4596 break;
4597 case ZFS_DELEG_NOTE_USERPROP:
4598 str = gettext("Allows changing any user property");
4599 break;
4600 case ZFS_DELEG_NOTE_USERQUOTA:
4601 str = gettext("Allows accessing any userquota@... property");
4602 break;
4603 case ZFS_DELEG_NOTE_USERUSED:
4604 str = gettext("Allows reading any userused@... property");
4605 break;
4606 /* other */
4607 default:
4608 str = "";
4609 }
4610
4611 return (str);
4612 }
4613
4614 struct allow_opts {
4615 boolean_t local;
4616 boolean_t descend;
4617 boolean_t user;
4618 boolean_t group;
4619 boolean_t everyone;
4620 boolean_t create;
4621 boolean_t set;
4622 boolean_t recursive; /* unallow only */
4623 boolean_t prt_usage;
4624
4625 boolean_t prt_perms;
4626 char *who;
4627 char *perms;
4628 const char *dataset;
4629 };
4630
4631 static inline int
4632 prop_cmp(const void *a, const void *b)
4633 {
4634 const char *str1 = *(const char **)a;
4635 const char *str2 = *(const char **)b;
4636 return (strcmp(str1, str2));
4637 }
4638
4639 static void
4640 allow_usage(boolean_t un, boolean_t requested, const char *msg)
4641 {
4642 const char *opt_desc[] = {
4643 "-h", gettext("show this help message and exit"),
4644 "-l", gettext("set permission locally"),
4645 "-d", gettext("set permission for descents"),
4646 "-u", gettext("set permission for user"),
4647 "-g", gettext("set permission for group"),
4648 "-e", gettext("set permission for everyone"),
4649 "-c", gettext("set create time permission"),
4650 "-s", gettext("define permission set"),
4651 /* unallow only */
4652 "-r", gettext("remove permissions recursively"),
4653 };
4654 size_t unallow_size = sizeof (opt_desc) / sizeof (char *);
4655 size_t allow_size = unallow_size - 2;
4656 const char *props[ZFS_NUM_PROPS];
4657 int i;
4658 size_t count = 0;
4659 FILE *fp = requested ? stdout : stderr;
4660 zprop_desc_t *pdtbl = zfs_prop_get_table();
4661 const char *fmt = gettext("%-16s %-14s\t%s\n");
4662
4663 (void) fprintf(fp, gettext("Usage: %s\n"), get_usage(un ? HELP_UNALLOW :
4664 HELP_ALLOW));
4665 (void) fprintf(fp, gettext("Options:\n"));
4666 for (i = 0; i < (un ? unallow_size : allow_size); i++) {
4667 const char *opt = opt_desc[i++];
4668 const char *optdsc = opt_desc[i];
4669 (void) fprintf(fp, gettext(" %-10s %s\n"), opt, optdsc);
4670 }
4671
4672 (void) fprintf(fp, gettext("\nThe following permissions are "
4673 "supported:\n\n"));
4674 (void) fprintf(fp, fmt, gettext("NAME"), gettext("TYPE"),
4675 gettext("NOTES"));
4676 for (i = 0; i < ZFS_NUM_DELEG_NOTES; i++) {
4677 const char *perm_name = zfs_deleg_perm_tbl[i].z_perm;
4678 zfs_deleg_note_t perm_note = zfs_deleg_perm_tbl[i].z_note;
4679 const char *perm_type = deleg_perm_type(perm_note);
4680 const char *perm_comment = deleg_perm_comment(perm_note);
4681 (void) fprintf(fp, fmt, perm_name, perm_type, perm_comment);
4682 }
4683
4684 for (i = 0; i < ZFS_NUM_PROPS; i++) {
4685 zprop_desc_t *pd = &pdtbl[i];
4686 if (pd->pd_visible != B_TRUE)
4687 continue;
4688
4689 if (pd->pd_attr == PROP_READONLY)
4690 continue;
4691
4692 props[count++] = pd->pd_name;
4693 }
4694 props[count] = NULL;
4695
4696 qsort(props, count, sizeof (char *), prop_cmp);
4697
4698 for (i = 0; i < count; i++)
4699 (void) fprintf(fp, fmt, props[i], gettext("property"), "");
4700
4701 if (msg != NULL)
4702 (void) fprintf(fp, gettext("\nzfs: error: %s"), msg);
4703
4704 exit(requested ? 0 : 2);
4705 }
4706
4707 static inline const char *
4708 munge_args(int argc, char **argv, boolean_t un, size_t expected_argc,
4709 char **permsp)
4710 {
4711 if (un && argc == expected_argc - 1)
4712 *permsp = NULL;
4713 else if (argc == expected_argc)
4714 *permsp = argv[argc - 2];
4715 else
4716 allow_usage(un, B_FALSE,
4717 gettext("wrong number of parameters\n"));
4718
4719 return (argv[argc - 1]);
4720 }
4721
4722 static void
4723 parse_allow_args(int argc, char **argv, boolean_t un, struct allow_opts *opts)
4724 {
4725 int uge_sum = opts->user + opts->group + opts->everyone;
4726 int csuge_sum = opts->create + opts->set + uge_sum;
4727 int ldcsuge_sum = csuge_sum + opts->local + opts->descend;
4728 int all_sum = un ? ldcsuge_sum + opts->recursive : ldcsuge_sum;
4729
4730 if (uge_sum > 1)
4731 allow_usage(un, B_FALSE,
4732 gettext("-u, -g, and -e are mutually exclusive\n"));
4733
4734 if (opts->prt_usage) {
4735 if (argc == 0 && all_sum == 0)
4736 allow_usage(un, B_TRUE, NULL);
4737 else
4738 usage(B_FALSE);
4739 }
4740
4741 if (opts->set) {
4742 if (csuge_sum > 1)
4743 allow_usage(un, B_FALSE,
4744 gettext("invalid options combined with -s\n"));
4745
4746 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4747 if (argv[0][0] != '@')
4748 allow_usage(un, B_FALSE,
4749 gettext("invalid set name: missing '@' prefix\n"));
4750 opts->who = argv[0];
4751 } else if (opts->create) {
4752 if (ldcsuge_sum > 1)
4753 allow_usage(un, B_FALSE,
4754 gettext("invalid options combined with -c\n"));
4755 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4756 } else if (opts->everyone) {
4757 if (csuge_sum > 1)
4758 allow_usage(un, B_FALSE,
4759 gettext("invalid options combined with -e\n"));
4760 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4761 } else if (uge_sum == 0 && argc > 0 && strcmp(argv[0], "everyone")
4762 == 0) {
4763 opts->everyone = B_TRUE;
4764 argc--;
4765 argv++;
4766 opts->dataset = munge_args(argc, argv, un, 2, &opts->perms);
4767 } else if (argc == 1 && !un) {
4768 opts->prt_perms = B_TRUE;
4769 opts->dataset = argv[argc-1];
4770 } else {
4771 opts->dataset = munge_args(argc, argv, un, 3, &opts->perms);
4772 opts->who = argv[0];
4773 }
4774
4775 if (!opts->local && !opts->descend) {
4776 opts->local = B_TRUE;
4777 opts->descend = B_TRUE;
4778 }
4779 }
4780
4781 static void
4782 store_allow_perm(zfs_deleg_who_type_t type, boolean_t local, boolean_t descend,
4783 const char *who, char *perms, nvlist_t *top_nvl)
4784 {
4785 int i;
4786 char ld[2] = { '\0', '\0' };
4787 char who_buf[ZFS_MAXNAMELEN+32];
4788 char base_type = ZFS_DELEG_WHO_UNKNOWN;
4789 char set_type = ZFS_DELEG_WHO_UNKNOWN;
4790 nvlist_t *base_nvl = NULL;
4791 nvlist_t *set_nvl = NULL;
4792 nvlist_t *nvl;
4793
4794 if (nvlist_alloc(&base_nvl, NV_UNIQUE_NAME, 0) != 0)
4795 nomem();
4796 if (nvlist_alloc(&set_nvl, NV_UNIQUE_NAME, 0) != 0)
4797 nomem();
4798
4799 switch (type) {
4800 case ZFS_DELEG_NAMED_SET_SETS:
4801 case ZFS_DELEG_NAMED_SET:
4802 set_type = ZFS_DELEG_NAMED_SET_SETS;
4803 base_type = ZFS_DELEG_NAMED_SET;
4804 ld[0] = ZFS_DELEG_NA;
4805 break;
4806 case ZFS_DELEG_CREATE_SETS:
4807 case ZFS_DELEG_CREATE:
4808 set_type = ZFS_DELEG_CREATE_SETS;
4809 base_type = ZFS_DELEG_CREATE;
4810 ld[0] = ZFS_DELEG_NA;
4811 break;
4812 case ZFS_DELEG_USER_SETS:
4813 case ZFS_DELEG_USER:
4814 set_type = ZFS_DELEG_USER_SETS;
4815 base_type = ZFS_DELEG_USER;
4816 if (local)
4817 ld[0] = ZFS_DELEG_LOCAL;
4818 if (descend)
4819 ld[1] = ZFS_DELEG_DESCENDENT;
4820 break;
4821 case ZFS_DELEG_GROUP_SETS:
4822 case ZFS_DELEG_GROUP:
4823 set_type = ZFS_DELEG_GROUP_SETS;
4824 base_type = ZFS_DELEG_GROUP;
4825 if (local)
4826 ld[0] = ZFS_DELEG_LOCAL;
4827 if (descend)
4828 ld[1] = ZFS_DELEG_DESCENDENT;
4829 break;
4830 case ZFS_DELEG_EVERYONE_SETS:
4831 case ZFS_DELEG_EVERYONE:
4832 set_type = ZFS_DELEG_EVERYONE_SETS;
4833 base_type = ZFS_DELEG_EVERYONE;
4834 if (local)
4835 ld[0] = ZFS_DELEG_LOCAL;
4836 if (descend)
4837 ld[1] = ZFS_DELEG_DESCENDENT;
4838 default:
4839 break;
4840 }
4841
4842 if (perms != NULL) {
4843 char *curr = perms;
4844 char *end = curr + strlen(perms);
4845
4846 while (curr < end) {
4847 char *delim = strchr(curr, ',');
4848 if (delim == NULL)
4849 delim = end;
4850 else
4851 *delim = '\0';
4852
4853 if (curr[0] == '@')
4854 nvl = set_nvl;
4855 else
4856 nvl = base_nvl;
4857
4858 (void) nvlist_add_boolean(nvl, curr);
4859 if (delim != end)
4860 *delim = ',';
4861 curr = delim + 1;
4862 }
4863
4864 for (i = 0; i < 2; i++) {
4865 char locality = ld[i];
4866 if (locality == 0)
4867 continue;
4868
4869 if (!nvlist_empty(base_nvl)) {
4870 if (who != NULL)
4871 (void) snprintf(who_buf,
4872 sizeof (who_buf), "%c%c$%s",
4873 base_type, locality, who);
4874 else
4875 (void) snprintf(who_buf,
4876 sizeof (who_buf), "%c%c$",
4877 base_type, locality);
4878
4879 (void) nvlist_add_nvlist(top_nvl, who_buf,
4880 base_nvl);
4881 }
4882
4883
4884 if (!nvlist_empty(set_nvl)) {
4885 if (who != NULL)
4886 (void) snprintf(who_buf,
4887 sizeof (who_buf), "%c%c$%s",
4888 set_type, locality, who);
4889 else
4890 (void) snprintf(who_buf,
4891 sizeof (who_buf), "%c%c$",
4892 set_type, locality);
4893
4894 (void) nvlist_add_nvlist(top_nvl, who_buf,
4895 set_nvl);
4896 }
4897 }
4898 } else {
4899 for (i = 0; i < 2; i++) {
4900 char locality = ld[i];
4901 if (locality == 0)
4902 continue;
4903
4904 if (who != NULL)
4905 (void) snprintf(who_buf, sizeof (who_buf),
4906 "%c%c$%s", base_type, locality, who);
4907 else
4908 (void) snprintf(who_buf, sizeof (who_buf),
4909 "%c%c$", base_type, locality);
4910 (void) nvlist_add_boolean(top_nvl, who_buf);
4911
4912 if (who != NULL)
4913 (void) snprintf(who_buf, sizeof (who_buf),
4914 "%c%c$%s", set_type, locality, who);
4915 else
4916 (void) snprintf(who_buf, sizeof (who_buf),
4917 "%c%c$", set_type, locality);
4918 (void) nvlist_add_boolean(top_nvl, who_buf);
4919 }
4920 }
4921 }
4922
4923 static int
4924 construct_fsacl_list(boolean_t un, struct allow_opts *opts, nvlist_t **nvlp)
4925 {
4926 if (nvlist_alloc(nvlp, NV_UNIQUE_NAME, 0) != 0)
4927 nomem();
4928
4929 if (opts->set) {
4930 store_allow_perm(ZFS_DELEG_NAMED_SET, opts->local,
4931 opts->descend, opts->who, opts->perms, *nvlp);
4932 } else if (opts->create) {
4933 store_allow_perm(ZFS_DELEG_CREATE, opts->local,
4934 opts->descend, NULL, opts->perms, *nvlp);
4935 } else if (opts->everyone) {
4936 store_allow_perm(ZFS_DELEG_EVERYONE, opts->local,
4937 opts->descend, NULL, opts->perms, *nvlp);
4938 } else {
4939 char *curr = opts->who;
4940 char *end = curr + strlen(curr);
4941
4942 while (curr < end) {
4943 const char *who;
4944 zfs_deleg_who_type_t who_type = ZFS_DELEG_WHO_UNKNOWN;
4945 char *endch;
4946 char *delim = strchr(curr, ',');
4947 char errbuf[256];
4948 char id[64];
4949 struct passwd *p = NULL;
4950 struct group *g = NULL;
4951
4952 uid_t rid;
4953 if (delim == NULL)
4954 delim = end;
4955 else
4956 *delim = '\0';
4957
4958 rid = (uid_t)strtol(curr, &endch, 0);
4959 if (opts->user) {
4960 who_type = ZFS_DELEG_USER;
4961 if (*endch != '\0')
4962 p = getpwnam(curr);
4963 else
4964 p = getpwuid(rid);
4965
4966 if (p != NULL)
4967 rid = p->pw_uid;
4968 else {
4969 (void) snprintf(errbuf, 256, gettext(
4970 "invalid user %s"), curr);
4971 allow_usage(un, B_TRUE, errbuf);
4972 }
4973 } else if (opts->group) {
4974 who_type = ZFS_DELEG_GROUP;
4975 if (*endch != '\0')
4976 g = getgrnam(curr);
4977 else
4978 g = getgrgid(rid);
4979
4980 if (g != NULL)
4981 rid = g->gr_gid;
4982 else {
4983 (void) snprintf(errbuf, 256, gettext(
4984 "invalid group %s"), curr);
4985 allow_usage(un, B_TRUE, errbuf);
4986 }
4987 } else {
4988 if (*endch != '\0') {
4989 p = getpwnam(curr);
4990 } else {
4991 p = getpwuid(rid);
4992 }
4993
4994 if (p == NULL) {
4995 if (*endch != '\0') {
4996 g = getgrnam(curr);
4997 } else {
4998 g = getgrgid(rid);
4999 }
5000 }
5001
5002 if (p != NULL) {
5003 who_type = ZFS_DELEG_USER;
5004 rid = p->pw_uid;
5005 } else if (g != NULL) {
5006 who_type = ZFS_DELEG_GROUP;
5007 rid = g->gr_gid;
5008 } else {
5009 (void) snprintf(errbuf, 256, gettext(
5010 "invalid user/group %s"), curr);
5011 allow_usage(un, B_TRUE, errbuf);
5012 }
5013 }
5014
5015 (void) sprintf(id, "%u", rid);
5016 who = id;
5017
5018 store_allow_perm(who_type, opts->local,
5019 opts->descend, who, opts->perms, *nvlp);
5020 curr = delim + 1;
5021 }
5022 }
5023
5024 return (0);
5025 }
5026
5027 static void
5028 print_set_creat_perms(uu_avl_t *who_avl)
5029 {
5030 const char *sc_title[] = {
5031 gettext("Permission sets:\n"),
5032 gettext("Create time permissions:\n"),
5033 NULL
5034 };
5035 const char **title_ptr = sc_title;
5036 who_perm_node_t *who_node = NULL;
5037 int prev_weight = -1;
5038
5039 for (who_node = uu_avl_first(who_avl); who_node != NULL;
5040 who_node = uu_avl_next(who_avl, who_node)) {
5041 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5042 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5043 const char *who_name = who_node->who_perm.who_name;
5044 int weight = who_type2weight(who_type);
5045 boolean_t first = B_TRUE;
5046 deleg_perm_node_t *deleg_node;
5047
5048 if (prev_weight != weight) {
5049 (void) printf("%s", *title_ptr++);
5050 prev_weight = weight;
5051 }
5052
5053 if (who_name == NULL || strnlen(who_name, 1) == 0)
5054 (void) printf("\t");
5055 else
5056 (void) printf("\t%s ", who_name);
5057
5058 for (deleg_node = uu_avl_first(avl); deleg_node != NULL;
5059 deleg_node = uu_avl_next(avl, deleg_node)) {
5060 if (first) {
5061 (void) printf("%s",
5062 deleg_node->dpn_perm.dp_name);
5063 first = B_FALSE;
5064 } else
5065 (void) printf(",%s",
5066 deleg_node->dpn_perm.dp_name);
5067 }
5068
5069 (void) printf("\n");
5070 }
5071 }
5072
5073 static void inline
5074 print_uge_deleg_perms(uu_avl_t *who_avl, boolean_t local, boolean_t descend,
5075 const char *title)
5076 {
5077 who_perm_node_t *who_node = NULL;
5078 boolean_t prt_title = B_TRUE;
5079 uu_avl_walk_t *walk;
5080
5081 if ((walk = uu_avl_walk_start(who_avl, UU_WALK_ROBUST)) == NULL)
5082 nomem();
5083
5084 while ((who_node = uu_avl_walk_next(walk)) != NULL) {
5085 const char *who_name = who_node->who_perm.who_name;
5086 const char *nice_who_name = who_node->who_perm.who_ug_name;
5087 uu_avl_t *avl = who_node->who_perm.who_deleg_perm_avl;
5088 zfs_deleg_who_type_t who_type = who_node->who_perm.who_type;
5089 char delim = ' ';
5090 deleg_perm_node_t *deleg_node;
5091 boolean_t prt_who = B_TRUE;
5092
5093 for (deleg_node = uu_avl_first(avl);
5094 deleg_node != NULL;
5095 deleg_node = uu_avl_next(avl, deleg_node)) {
5096 if (local != deleg_node->dpn_perm.dp_local ||
5097 descend != deleg_node->dpn_perm.dp_descend)
5098 continue;
5099
5100 if (prt_who) {
5101 const char *who = NULL;
5102 if (prt_title) {
5103 prt_title = B_FALSE;
5104 (void) printf("%s", title);
5105 }
5106
5107 switch (who_type) {
5108 case ZFS_DELEG_USER_SETS:
5109 case ZFS_DELEG_USER:
5110 who = gettext("user");
5111 if (nice_who_name)
5112 who_name = nice_who_name;
5113 break;
5114 case ZFS_DELEG_GROUP_SETS:
5115 case ZFS_DELEG_GROUP:
5116 who = gettext("group");
5117 if (nice_who_name)
5118 who_name = nice_who_name;
5119 break;
5120 case ZFS_DELEG_EVERYONE_SETS:
5121 case ZFS_DELEG_EVERYONE:
5122 who = gettext("everyone");
5123 who_name = NULL;
5124 default:
5125 break;
5126 }
5127
5128 prt_who = B_FALSE;
5129 if (who_name == NULL)
5130 (void) printf("\t%s", who);
5131 else
5132 (void) printf("\t%s %s", who, who_name);
5133 }
5134
5135 (void) printf("%c%s", delim,
5136 deleg_node->dpn_perm.dp_name);
5137 delim = ',';
5138 }
5139
5140 if (!prt_who)
5141 (void) printf("\n");
5142 }
5143
5144 uu_avl_walk_end(walk);
5145 }
5146
5147 static void
5148 print_fs_perms(fs_perm_set_t *fspset)
5149 {
5150 fs_perm_node_t *node = NULL;
5151 char buf[ZFS_MAXNAMELEN+32];
5152 const char *dsname = buf;
5153
5154 for (node = uu_list_first(fspset->fsps_list); node != NULL;
5155 node = uu_list_next(fspset->fsps_list, node)) {
5156 uu_avl_t *sc_avl = node->fspn_fsperm.fsp_sc_avl;
5157 uu_avl_t *uge_avl = node->fspn_fsperm.fsp_uge_avl;
5158 int left = 0;
5159
5160 (void) snprintf(buf, ZFS_MAXNAMELEN+32,
5161 gettext("---- Permissions on %s "),
5162 node->fspn_fsperm.fsp_name);
5163 (void) printf("%s", dsname);
5164 left = 70 - strlen(buf);
5165 while (left-- > 0)
5166 (void) printf("-");
5167 (void) printf("\n");
5168
5169 print_set_creat_perms(sc_avl);
5170 print_uge_deleg_perms(uge_avl, B_TRUE, B_FALSE,
5171 gettext("Local permissions:\n"));
5172 print_uge_deleg_perms(uge_avl, B_FALSE, B_TRUE,
5173 gettext("Descendent permissions:\n"));
5174 print_uge_deleg_perms(uge_avl, B_TRUE, B_TRUE,
5175 gettext("Local+Descendent permissions:\n"));
5176 }
5177 }
5178
5179 static fs_perm_set_t fs_perm_set = { NULL, NULL, NULL, NULL };
5180
5181 struct deleg_perms {
5182 boolean_t un;
5183 nvlist_t *nvl;
5184 };
5185
5186 static int
5187 set_deleg_perms(zfs_handle_t *zhp, void *data)
5188 {
5189 struct deleg_perms *perms = (struct deleg_perms *)data;
5190 zfs_type_t zfs_type = zfs_get_type(zhp);
5191
5192 if (zfs_type != ZFS_TYPE_FILESYSTEM && zfs_type != ZFS_TYPE_VOLUME)
5193 return (0);
5194
5195 return (zfs_set_fsacl(zhp, perms->un, perms->nvl));
5196 }
5197
5198 static int
5199 zfs_do_allow_unallow_impl(int argc, char **argv, boolean_t un)
5200 {
5201 zfs_handle_t *zhp;
5202 nvlist_t *perm_nvl = NULL;
5203 nvlist_t *update_perm_nvl = NULL;
5204 int error = 1;
5205 int c;
5206 struct allow_opts opts = { 0 };
5207
5208 const char *optstr = un ? "ldugecsrh" : "ldugecsh";
5209
5210 /* check opts */
5211 while ((c = getopt(argc, argv, optstr)) != -1) {
5212 switch (c) {
5213 case 'l':
5214 opts.local = B_TRUE;
5215 break;
5216 case 'd':
5217 opts.descend = B_TRUE;
5218 break;
5219 case 'u':
5220 opts.user = B_TRUE;
5221 break;
5222 case 'g':
5223 opts.group = B_TRUE;
5224 break;
5225 case 'e':
5226 opts.everyone = B_TRUE;
5227 break;
5228 case 's':
5229 opts.set = B_TRUE;
5230 break;
5231 case 'c':
5232 opts.create = B_TRUE;
5233 break;
5234 case 'r':
5235 opts.recursive = B_TRUE;
5236 break;
5237 case ':':
5238 (void) fprintf(stderr, gettext("missing argument for "
5239 "'%c' option\n"), optopt);
5240 usage(B_FALSE);
5241 break;
5242 case 'h':
5243 opts.prt_usage = B_TRUE;
5244 break;
5245 case '?':
5246 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5247 optopt);
5248 usage(B_FALSE);
5249 }
5250 }
5251
5252 argc -= optind;
5253 argv += optind;
5254
5255 /* check arguments */
5256 parse_allow_args(argc, argv, un, &opts);
5257
5258 /* try to open the dataset */
5259 if ((zhp = zfs_open(g_zfs, opts.dataset, ZFS_TYPE_FILESYSTEM |
5260 ZFS_TYPE_VOLUME)) == NULL) {
5261 (void) fprintf(stderr, "Failed to open dataset: %s\n",
5262 opts.dataset);
5263 return (-1);
5264 }
5265
5266 if (zfs_get_fsacl(zhp, &perm_nvl) != 0)
5267 goto cleanup2;
5268
5269 fs_perm_set_init(&fs_perm_set);
5270 if (parse_fs_perm_set(&fs_perm_set, perm_nvl) != 0) {
5271 (void) fprintf(stderr, "Failed to parse fsacl permissions\n");
5272 goto cleanup1;
5273 }
5274
5275 if (opts.prt_perms)
5276 print_fs_perms(&fs_perm_set);
5277 else {
5278 (void) construct_fsacl_list(un, &opts, &update_perm_nvl);
5279 if (zfs_set_fsacl(zhp, un, update_perm_nvl) != 0)
5280 goto cleanup0;
5281
5282 if (un && opts.recursive) {
5283 struct deleg_perms data = { un, update_perm_nvl };
5284 if (zfs_iter_filesystems(zhp, set_deleg_perms,
5285 &data) != 0)
5286 goto cleanup0;
5287 }
5288 }
5289
5290 error = 0;
5291
5292 cleanup0:
5293 nvlist_free(perm_nvl);
5294 if (update_perm_nvl != NULL)
5295 nvlist_free(update_perm_nvl);
5296 cleanup1:
5297 fs_perm_set_fini(&fs_perm_set);
5298 cleanup2:
5299 zfs_close(zhp);
5300
5301 return (error);
5302 }
5303
5304 static int
5305 zfs_do_allow(int argc, char **argv)
5306 {
5307 return (zfs_do_allow_unallow_impl(argc, argv, B_FALSE));
5308 }
5309
5310 static int
5311 zfs_do_unallow(int argc, char **argv)
5312 {
5313 return (zfs_do_allow_unallow_impl(argc, argv, B_TRUE));
5314 }
5315
5316 static int
5317 zfs_do_hold_rele_impl(int argc, char **argv, boolean_t holding)
5318 {
5319 int errors = 0;
5320 int i;
5321 const char *tag;
5322 boolean_t recursive = B_FALSE;
5323 const char *opts = holding ? "rt" : "r";
5324 int c;
5325
5326 /* check options */
5327 while ((c = getopt(argc, argv, opts)) != -1) {
5328 switch (c) {
5329 case 'r':
5330 recursive = B_TRUE;
5331 break;
5332 case '?':
5333 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5334 optopt);
5335 usage(B_FALSE);
5336 }
5337 }
5338
5339 argc -= optind;
5340 argv += optind;
5341
5342 /* check number of arguments */
5343 if (argc < 2)
5344 usage(B_FALSE);
5345
5346 tag = argv[0];
5347 --argc;
5348 ++argv;
5349
5350 if (holding && tag[0] == '.') {
5351 /* tags starting with '.' are reserved for libzfs */
5352 (void) fprintf(stderr, gettext("tag may not start with '.'\n"));
5353 usage(B_FALSE);
5354 }
5355
5356 for (i = 0; i < argc; ++i) {
5357 zfs_handle_t *zhp;
5358 char parent[ZFS_MAXNAMELEN];
5359 const char *delim;
5360 char *path = argv[i];
5361
5362 delim = strchr(path, '@');
5363 if (delim == NULL) {
5364 (void) fprintf(stderr,
5365 gettext("'%s' is not a snapshot\n"), path);
5366 ++errors;
5367 continue;
5368 }
5369 (void) strncpy(parent, path, delim - path);
5370 parent[delim - path] = '\0';
5371
5372 zhp = zfs_open(g_zfs, parent,
5373 ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5374 if (zhp == NULL) {
5375 ++errors;
5376 continue;
5377 }
5378 if (holding) {
5379 if (zfs_hold(zhp, delim+1, tag, recursive, -1) != 0)
5380 ++errors;
5381 } else {
5382 if (zfs_release(zhp, delim+1, tag, recursive) != 0)
5383 ++errors;
5384 }
5385 zfs_close(zhp);
5386 }
5387
5388 return (errors != 0);
5389 }
5390
5391 /*
5392 * zfs hold [-r] [-t] <tag> <snap> ...
5393 *
5394 * -r Recursively hold
5395 *
5396 * Apply a user-hold with the given tag to the list of snapshots.
5397 */
5398 static int
5399 zfs_do_hold(int argc, char **argv)
5400 {
5401 return (zfs_do_hold_rele_impl(argc, argv, B_TRUE));
5402 }
5403
5404 /*
5405 * zfs release [-r] <tag> <snap> ...
5406 *
5407 * -r Recursively release
5408 *
5409 * Release a user-hold with the given tag from the list of snapshots.
5410 */
5411 static int
5412 zfs_do_release(int argc, char **argv)
5413 {
5414 return (zfs_do_hold_rele_impl(argc, argv, B_FALSE));
5415 }
5416
5417 typedef struct holds_cbdata {
5418 boolean_t cb_recursive;
5419 const char *cb_snapname;
5420 nvlist_t **cb_nvlp;
5421 size_t cb_max_namelen;
5422 size_t cb_max_taglen;
5423 } holds_cbdata_t;
5424
5425 #define STRFTIME_FMT_STR "%a %b %e %k:%M %Y"
5426 #define DATETIME_BUF_LEN (32)
5427 /*
5428 *
5429 */
5430 static void
5431 print_holds(boolean_t scripted, int nwidth, int tagwidth, nvlist_t *nvl)
5432 {
5433 int i;
5434 nvpair_t *nvp = NULL;
5435 char *hdr_cols[] = { "NAME", "TAG", "TIMESTAMP" };
5436 const char *col;
5437
5438 if (!scripted) {
5439 for (i = 0; i < 3; i++) {
5440 col = gettext(hdr_cols[i]);
5441 if (i < 2)
5442 (void) printf("%-*s ", i ? tagwidth : nwidth,
5443 col);
5444 else
5445 (void) printf("%s\n", col);
5446 }
5447 }
5448
5449 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5450 char *zname = nvpair_name(nvp);
5451 nvlist_t *nvl2;
5452 nvpair_t *nvp2 = NULL;
5453 (void) nvpair_value_nvlist(nvp, &nvl2);
5454 while ((nvp2 = nvlist_next_nvpair(nvl2, nvp2)) != NULL) {
5455 char tsbuf[DATETIME_BUF_LEN];
5456 char *tagname = nvpair_name(nvp2);
5457 uint64_t val = 0;
5458 time_t time;
5459 struct tm t;
5460 char sep = scripted ? '\t' : ' ';
5461 int sepnum = scripted ? 1 : 2;
5462
5463 (void) nvpair_value_uint64(nvp2, &val);
5464 time = (time_t)val;
5465 (void) localtime_r(&time, &t);
5466 (void) strftime(tsbuf, DATETIME_BUF_LEN,
5467 gettext(STRFTIME_FMT_STR), &t);
5468
5469 (void) printf("%-*s%*c%-*s%*c%s\n", nwidth, zname,
5470 sepnum, sep, tagwidth, tagname, sepnum, sep, tsbuf);
5471 }
5472 }
5473 }
5474
5475 /*
5476 * Generic callback function to list a dataset or snapshot.
5477 */
5478 static int
5479 holds_callback(zfs_handle_t *zhp, void *data)
5480 {
5481 holds_cbdata_t *cbp = data;
5482 nvlist_t *top_nvl = *cbp->cb_nvlp;
5483 nvlist_t *nvl = NULL;
5484 nvpair_t *nvp = NULL;
5485 const char *zname = zfs_get_name(zhp);
5486 size_t znamelen = strnlen(zname, ZFS_MAXNAMELEN);
5487
5488 if (cbp->cb_recursive) {
5489 const char *snapname;
5490 char *delim = strchr(zname, '@');
5491 if (delim == NULL)
5492 return (0);
5493
5494 snapname = delim + 1;
5495 if (strcmp(cbp->cb_snapname, snapname))
5496 return (0);
5497 }
5498
5499 if (zfs_get_holds(zhp, &nvl) != 0)
5500 return (-1);
5501
5502 if (znamelen > cbp->cb_max_namelen)
5503 cbp->cb_max_namelen = znamelen;
5504
5505 while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
5506 const char *tag = nvpair_name(nvp);
5507 size_t taglen = strnlen(tag, MAXNAMELEN);
5508 if (taglen > cbp->cb_max_taglen)
5509 cbp->cb_max_taglen = taglen;
5510 }
5511
5512 return (nvlist_add_nvlist(top_nvl, zname, nvl));
5513 }
5514
5515 /*
5516 * zfs holds [-r] <snap> ...
5517 *
5518 * -r Recursively hold
5519 */
5520 static int
5521 zfs_do_holds(int argc, char **argv)
5522 {
5523 int errors = 0;
5524 int c;
5525 int i;
5526 boolean_t scripted = B_FALSE;
5527 boolean_t recursive = B_FALSE;
5528 const char *opts = "rH";
5529 nvlist_t *nvl;
5530
5531 int types = ZFS_TYPE_SNAPSHOT;
5532 holds_cbdata_t cb = { 0 };
5533
5534 int limit = 0;
5535 int ret = 0;
5536 int flags = 0;
5537
5538 /* check options */
5539 while ((c = getopt(argc, argv, opts)) != -1) {
5540 switch (c) {
5541 case 'r':
5542 recursive = B_TRUE;
5543 break;
5544 case 'H':
5545 scripted = B_TRUE;
5546 break;
5547 case '?':
5548 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5549 optopt);
5550 usage(B_FALSE);
5551 }
5552 }
5553
5554 if (recursive) {
5555 types |= ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME;
5556 flags |= ZFS_ITER_RECURSE;
5557 }
5558
5559 argc -= optind;
5560 argv += optind;
5561
5562 /* check number of arguments */
5563 if (argc < 1)
5564 usage(B_FALSE);
5565
5566 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
5567 nomem();
5568
5569 for (i = 0; i < argc; ++i) {
5570 char *snapshot = argv[i];
5571 const char *delim;
5572 const char *snapname;
5573
5574 delim = strchr(snapshot, '@');
5575 if (delim == NULL) {
5576 (void) fprintf(stderr,
5577 gettext("'%s' is not a snapshot\n"), snapshot);
5578 ++errors;
5579 continue;
5580 }
5581 snapname = delim + 1;
5582 if (recursive)
5583 snapshot[delim - snapshot] = '\0';
5584
5585 cb.cb_recursive = recursive;
5586 cb.cb_snapname = snapname;
5587 cb.cb_nvlp = &nvl;
5588
5589 /*
5590 * 1. collect holds data, set format options
5591 */
5592 ret = zfs_for_each(argc, argv, flags, types, NULL, NULL, limit,
5593 holds_callback, &cb);
5594 if (ret != 0)
5595 ++errors;
5596 }
5597
5598 /*
5599 * 2. print holds data
5600 */
5601 print_holds(scripted, cb.cb_max_namelen, cb.cb_max_taglen, nvl);
5602
5603 if (nvlist_empty(nvl))
5604 (void) fprintf(stderr, gettext("no datasets available\n"));
5605
5606 nvlist_free(nvl);
5607
5608 return (0 != errors);
5609 }
5610
5611 #define CHECK_SPINNER 30
5612 #define SPINNER_TIME 3 /* seconds */
5613 #define MOUNT_TIME 5 /* seconds */
5614
5615 static int
5616 get_one_dataset(zfs_handle_t *zhp, void *data)
5617 {
5618 static char *spin[] = { "-", "\\", "|", "/" };
5619 static int spinval = 0;
5620 static int spincheck = 0;
5621 static time_t last_spin_time = (time_t)0;
5622 get_all_cb_t *cbp = data;
5623 zfs_type_t type = zfs_get_type(zhp);
5624
5625 if (cbp->cb_verbose) {
5626 if (--spincheck < 0) {
5627 time_t now = time(NULL);
5628 if (last_spin_time + SPINNER_TIME < now) {
5629 update_progress(spin[spinval++ % 4]);
5630 last_spin_time = now;
5631 }
5632 spincheck = CHECK_SPINNER;
5633 }
5634 }
5635
5636 /*
5637 * Iterate over any nested datasets.
5638 */
5639 if (zfs_iter_filesystems(zhp, get_one_dataset, data) != 0) {
5640 zfs_close(zhp);
5641 return (1);
5642 }
5643
5644 /*
5645 * Skip any datasets whose type does not match.
5646 */
5647 if ((type & ZFS_TYPE_FILESYSTEM) == 0) {
5648 zfs_close(zhp);
5649 return (0);
5650 }
5651 libzfs_add_handle(cbp, zhp);
5652 assert(cbp->cb_used <= cbp->cb_alloc);
5653
5654 return (0);
5655 }
5656
5657 static void
5658 get_all_datasets(zfs_handle_t ***dslist, size_t *count, boolean_t verbose)
5659 {
5660 get_all_cb_t cb = { 0 };
5661 cb.cb_verbose = verbose;
5662 cb.cb_getone = get_one_dataset;
5663
5664 if (verbose)
5665 set_progress_header(gettext("Reading ZFS config"));
5666 (void) zfs_iter_root(g_zfs, get_one_dataset, &cb);
5667
5668 *dslist = cb.cb_handles;
5669 *count = cb.cb_used;
5670
5671 if (verbose)
5672 finish_progress(gettext("done."));
5673 }
5674
5675 /*
5676 * Generic callback for sharing or mounting filesystems. Because the code is so
5677 * similar, we have a common function with an extra parameter to determine which
5678 * mode we are using.
5679 */
5680 #define OP_SHARE 0x1
5681 #define OP_MOUNT 0x2
5682
5683 /*
5684 * Share or mount a dataset.
5685 */
5686 static int
5687 share_mount_one(zfs_handle_t *zhp, int op, int flags, char *protocol,
5688 boolean_t explicit, const char *options)
5689 {
5690 char mountpoint[ZFS_MAXPROPLEN];
5691 char shareopts[ZFS_MAXPROPLEN];
5692 char smbshareopts[ZFS_MAXPROPLEN];
5693 const char *cmdname = op == OP_SHARE ? "share" : "mount";
5694 struct mnttab mnt;
5695 uint64_t zoned, canmount;
5696 boolean_t shared_nfs, shared_smb;
5697
5698 assert(zfs_get_type(zhp) & ZFS_TYPE_FILESYSTEM);
5699
5700 /*
5701 * Check to make sure we can mount/share this dataset. If we
5702 * are in the global zone and the filesystem is exported to a
5703 * local zone, or if we are in a local zone and the
5704 * filesystem is not exported, then it is an error.
5705 */
5706 zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
5707
5708 if (zoned && getzoneid() == GLOBAL_ZONEID) {
5709 if (!explicit)
5710 return (0);
5711
5712 (void) fprintf(stderr, gettext("cannot %s '%s': "
5713 "dataset is exported to a local zone\n"), cmdname,
5714 zfs_get_name(zhp));
5715 return (1);
5716
5717 } else if (!zoned && getzoneid() != GLOBAL_ZONEID) {
5718 if (!explicit)
5719 return (0);
5720
5721 (void) fprintf(stderr, gettext("cannot %s '%s': "
5722 "permission denied\n"), cmdname,
5723 zfs_get_name(zhp));
5724 return (1);
5725 }
5726
5727 /*
5728 * Ignore any filesystems which don't apply to us. This
5729 * includes those with a legacy mountpoint, or those with
5730 * legacy share options.
5731 */
5732 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mountpoint,
5733 sizeof (mountpoint), NULL, NULL, 0, B_FALSE) == 0);
5734 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, shareopts,
5735 sizeof (shareopts), NULL, NULL, 0, B_FALSE) == 0);
5736 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshareopts,
5737 sizeof (smbshareopts), NULL, NULL, 0, B_FALSE) == 0);
5738
5739 if (op == OP_SHARE && strcmp(shareopts, "off") == 0 &&
5740 strcmp(smbshareopts, "off") == 0) {
5741 if (!explicit)
5742 return (0);
5743
5744 (void) fprintf(stderr, gettext("cannot share '%s': "
5745 "legacy share\n"), zfs_get_name(zhp));
5746 (void) fprintf(stderr, gettext("use share(1M) to "
5747 "share this filesystem, or set "
5748 "sharenfs property on\n"));
5749 return (1);
5750 }
5751
5752 /*
5753 * We cannot share or mount legacy filesystems. If the
5754 * shareopts is non-legacy but the mountpoint is legacy, we
5755 * treat it as a legacy share.
5756 */
5757 if (strcmp(mountpoint, "legacy") == 0) {
5758 if (!explicit)
5759 return (0);
5760
5761 (void) fprintf(stderr, gettext("cannot %s '%s': "
5762 "legacy mountpoint\n"), cmdname, zfs_get_name(zhp));
5763 (void) fprintf(stderr, gettext("use %s(1M) to "
5764 "%s this filesystem\n"), cmdname, cmdname);
5765 return (1);
5766 }
5767
5768 if (strcmp(mountpoint, "none") == 0) {
5769 if (!explicit)
5770 return (0);
5771
5772 (void) fprintf(stderr, gettext("cannot %s '%s': no "
5773 "mountpoint set\n"), cmdname, zfs_get_name(zhp));
5774 return (1);
5775 }
5776
5777 /*
5778 * canmount explicit outcome
5779 * on no pass through
5780 * on yes pass through
5781 * off no return 0
5782 * off yes display error, return 1
5783 * noauto no return 0
5784 * noauto yes pass through
5785 */
5786 canmount = zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT);
5787 if (canmount == ZFS_CANMOUNT_OFF) {
5788 if (!explicit)
5789 return (0);
5790
5791 (void) fprintf(stderr, gettext("cannot %s '%s': "
5792 "'canmount' property is set to 'off'\n"), cmdname,
5793 zfs_get_name(zhp));
5794 return (1);
5795 } else if (canmount == ZFS_CANMOUNT_NOAUTO && !explicit) {
5796 return (0);
5797 }
5798
5799 /*
5800 * At this point, we have verified that the mountpoint and/or
5801 * shareopts are appropriate for auto management. If the
5802 * filesystem is already mounted or shared, return (failing
5803 * for explicit requests); otherwise mount or share the
5804 * filesystem.
5805 */
5806 switch (op) {
5807 case OP_SHARE:
5808
5809 shared_nfs = zfs_is_shared_nfs(zhp, NULL);
5810 shared_smb = zfs_is_shared_smb(zhp, NULL);
5811
5812 if ((shared_nfs && shared_smb) ||
5813 ((shared_nfs && strcmp(shareopts, "on") == 0) &&
5814 (strcmp(smbshareopts, "off") == 0)) ||
5815 ((shared_smb && strcmp(smbshareopts, "on") == 0) &&
5816 (strcmp(shareopts, "off") == 0))) {
5817 if (!explicit)
5818 return (0);
5819
5820 (void) fprintf(stderr, gettext("cannot share "
5821 "'%s': filesystem already shared\n"),
5822 zfs_get_name(zhp));
5823 return (1);
5824 }
5825
5826 if (!zfs_is_mounted(zhp, NULL) &&
5827 zfs_mount(zhp, NULL, 0) != 0)
5828 return (1);
5829
5830 if (protocol == NULL) {
5831 if (zfs_shareall(zhp) != 0)
5832 return (1);
5833 } else if (strcmp(protocol, "nfs") == 0) {
5834 if (zfs_share_nfs(zhp))
5835 return (1);
5836 } else if (strcmp(protocol, "smb") == 0) {
5837 if (zfs_share_smb(zhp))
5838 return (1);
5839 } else {
5840 (void) fprintf(stderr, gettext("cannot share "
5841 "'%s': invalid share type '%s' "
5842 "specified\n"),
5843 zfs_get_name(zhp), protocol);
5844 return (1);
5845 }
5846
5847 break;
5848
5849 case OP_MOUNT:
5850 if (options == NULL)
5851 mnt.mnt_mntopts = "";
5852 else
5853 mnt.mnt_mntopts = (char *)options;
5854
5855 if (!hasmntopt(&mnt, MNTOPT_REMOUNT) &&
5856 zfs_is_mounted(zhp, NULL)) {
5857 if (!explicit)
5858 return (0);
5859
5860 (void) fprintf(stderr, gettext("cannot mount "
5861 "'%s': filesystem already mounted\n"),
5862 zfs_get_name(zhp));
5863 return (1);
5864 }
5865
5866 if (zfs_mount(zhp, options, flags) != 0)
5867 return (1);
5868 break;
5869 }
5870
5871 return (0);
5872 }
5873
5874 /*
5875 * Reports progress in the form "(current/total)". Not thread-safe.
5876 */
5877 static void
5878 report_mount_progress(int current, int total)
5879 {
5880 static time_t last_progress_time = 0;
5881 time_t now = time(NULL);
5882 char info[32];
5883
5884 /* report 1..n instead of 0..n-1 */
5885 ++current;
5886
5887 /* display header if we're here for the first time */
5888 if (current == 1) {
5889 set_progress_header(gettext("Mounting ZFS filesystems"));
5890 } else if (current != total && last_progress_time + MOUNT_TIME >= now) {
5891 /* too soon to report again */
5892 return;
5893 }
5894
5895 last_progress_time = now;
5896
5897 (void) sprintf(info, "(%d/%d)", current, total);
5898
5899 if (current == total)
5900 finish_progress(info);
5901 else
5902 update_progress(info);
5903 }
5904
5905 static void
5906 append_options(char *mntopts, char *newopts)
5907 {
5908 int len = strlen(mntopts);
5909
5910 /* original length plus new string to append plus 1 for the comma */
5911 if (len + 1 + strlen(newopts) >= MNT_LINE_MAX) {
5912 (void) fprintf(stderr, gettext("the opts argument for "
5913 "'%s' option is too long (more than %d chars)\n"),
5914 "-o", MNT_LINE_MAX);
5915 usage(B_FALSE);
5916 }
5917
5918 if (*mntopts)
5919 mntopts[len++] = ',';
5920
5921 (void) strcpy(&mntopts[len], newopts);
5922 }
5923
5924 static int
5925 share_mount(int op, int argc, char **argv)
5926 {
5927 int do_all = 0;
5928 boolean_t verbose = B_FALSE;
5929 int c, ret = 0;
5930 char *options = NULL;
5931 int flags = 0;
5932
5933 /* check options */
5934 while ((c = getopt(argc, argv, op == OP_MOUNT ? ":avo:O" : "a"))
5935 != -1) {
5936 switch (c) {
5937 case 'a':
5938 do_all = 1;
5939 break;
5940 case 'v':
5941 verbose = B_TRUE;
5942 break;
5943 case 'o':
5944 if (*optarg == '\0') {
5945 (void) fprintf(stderr, gettext("empty mount "
5946 "options (-o) specified\n"));
5947 usage(B_FALSE);
5948 }
5949
5950 if (options == NULL)
5951 options = safe_malloc(MNT_LINE_MAX + 1);
5952
5953 /* option validation is done later */
5954 append_options(options, optarg);
5955 break;
5956 case 'O':
5957 flags |= MS_OVERLAY;
5958 break;
5959 case ':':
5960 (void) fprintf(stderr, gettext("missing argument for "
5961 "'%c' option\n"), optopt);
5962 usage(B_FALSE);
5963 break;
5964 case '?':
5965 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
5966 optopt);
5967 usage(B_FALSE);
5968 }
5969 }
5970
5971 argc -= optind;
5972 argv += optind;
5973
5974 /* check number of arguments */
5975 if (do_all) {
5976 zfs_handle_t **dslist = NULL;
5977 size_t i, count = 0;
5978 char *protocol = NULL;
5979
5980 if (op == OP_SHARE && argc > 0) {
5981 if (strcmp(argv[0], "nfs") != 0 &&
5982 strcmp(argv[0], "smb") != 0) {
5983 (void) fprintf(stderr, gettext("share type "
5984 "must be 'nfs' or 'smb'\n"));
5985 usage(B_FALSE);
5986 }
5987 protocol = argv[0];
5988 argc--;
5989 argv++;
5990 }
5991
5992 if (argc != 0) {
5993 (void) fprintf(stderr, gettext("too many arguments\n"));
5994 usage(B_FALSE);
5995 }
5996
5997 start_progress_timer();
5998 get_all_datasets(&dslist, &count, verbose);
5999
6000 if (count == 0)
6001 return (0);
6002
6003 qsort(dslist, count, sizeof (void *), libzfs_dataset_cmp);
6004
6005 for (i = 0; i < count; i++) {
6006 if (verbose)
6007 report_mount_progress(i, count);
6008
6009 if (share_mount_one(dslist[i], op, flags, protocol,
6010 B_FALSE, options) != 0)
6011 ret = 1;
6012 zfs_close(dslist[i]);
6013 }
6014
6015 free(dslist);
6016 } else if (argc == 0) {
6017 struct mnttab entry;
6018
6019 if ((op == OP_SHARE) || (options != NULL)) {
6020 (void) fprintf(stderr, gettext("missing filesystem "
6021 "argument (specify -a for all)\n"));
6022 usage(B_FALSE);
6023 }
6024
6025 /*
6026 * When mount is given no arguments, go through /etc/mtab and
6027 * display any active ZFS mounts. We hide any snapshots, since
6028 * they are controlled automatically.
6029 */
6030
6031 /* Reopen MNTTAB to prevent reading stale data from open file */
6032 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
6033 return (ENOENT);
6034
6035 while (getmntent(mnttab_file, &entry) == 0) {
6036 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0 ||
6037 strchr(entry.mnt_special, '@') != NULL)
6038 continue;
6039
6040 (void) printf("%-30s %s\n", entry.mnt_special,
6041 entry.mnt_mountp);
6042 }
6043
6044 } else {
6045 zfs_handle_t *zhp;
6046
6047 if (argc > 1) {
6048 (void) fprintf(stderr,
6049 gettext("too many arguments\n"));
6050 usage(B_FALSE);
6051 }
6052
6053 if ((zhp = zfs_open(g_zfs, argv[0],
6054 ZFS_TYPE_FILESYSTEM)) == NULL) {
6055 ret = 1;
6056 } else {
6057 ret = share_mount_one(zhp, op, flags, NULL, B_TRUE,
6058 options);
6059 zfs_close(zhp);
6060 }
6061 }
6062
6063 return (ret);
6064 }
6065
6066 /*
6067 * zfs mount -a [nfs]
6068 * zfs mount filesystem
6069 *
6070 * Mount all filesystems, or mount the given filesystem.
6071 */
6072 static int
6073 zfs_do_mount(int argc, char **argv)
6074 {
6075 return (share_mount(OP_MOUNT, argc, argv));
6076 }
6077
6078 /*
6079 * zfs share -a [nfs | smb]
6080 * zfs share filesystem
6081 *
6082 * Share all filesystems, or share the given filesystem.
6083 */
6084 static int
6085 zfs_do_share(int argc, char **argv)
6086 {
6087 return (share_mount(OP_SHARE, argc, argv));
6088 }
6089
6090 typedef struct unshare_unmount_node {
6091 zfs_handle_t *un_zhp;
6092 char *un_mountp;
6093 uu_avl_node_t un_avlnode;
6094 } unshare_unmount_node_t;
6095
6096 /* ARGSUSED */
6097 static int
6098 unshare_unmount_compare(const void *larg, const void *rarg, void *unused)
6099 {
6100 const unshare_unmount_node_t *l = larg;
6101 const unshare_unmount_node_t *r = rarg;
6102
6103 return (strcmp(l->un_mountp, r->un_mountp));
6104 }
6105
6106 /*
6107 * Convenience routine used by zfs_do_umount() and manual_unmount(). Given an
6108 * absolute path, find the entry /etc/mtab, verify that its a ZFS filesystem,
6109 * and unmount it appropriately.
6110 */
6111 static int
6112 unshare_unmount_path(int op, char *path, int flags, boolean_t is_manual)
6113 {
6114 zfs_handle_t *zhp;
6115 int ret = 0;
6116 struct stat64 statbuf;
6117 struct extmnttab entry;
6118 const char *cmdname = (op == OP_SHARE) ? "unshare" : "unmount";
6119 ino_t path_inode;
6120
6121 /*
6122 * Search for the path in /etc/mtab. Rather than looking for the
6123 * specific path, which can be fooled by non-standard paths (i.e. ".."
6124 * or "//"), we stat() the path and search for the corresponding
6125 * (major,minor) device pair.
6126 */
6127 if (stat64(path, &statbuf) != 0) {
6128 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6129 cmdname, path, strerror(errno));
6130 return (1);
6131 }
6132 path_inode = statbuf.st_ino;
6133
6134 /*
6135 * Search for the given (major,minor) pair in the mount table.
6136 */
6137
6138 /* Reopen MNTTAB to prevent reading stale data from open file */
6139 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
6140 return (ENOENT);
6141
6142 while ((ret = getextmntent(mnttab_file, &entry, 0)) == 0) {
6143 if (entry.mnt_major == major(statbuf.st_dev) &&
6144 entry.mnt_minor == minor(statbuf.st_dev))
6145 break;
6146 }
6147 if (ret != 0) {
6148 if (op == OP_SHARE) {
6149 (void) fprintf(stderr, gettext("cannot %s '%s': not "
6150 "currently mounted\n"), cmdname, path);
6151 return (1);
6152 }
6153 (void) fprintf(stderr, gettext("warning: %s not in mtab\n"),
6154 path);
6155 if ((ret = umount2(path, flags)) != 0)
6156 (void) fprintf(stderr, gettext("%s: %s\n"), path,
6157 strerror(errno));
6158 return (ret != 0);
6159 }
6160
6161 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
6162 (void) fprintf(stderr, gettext("cannot %s '%s': not a ZFS "
6163 "filesystem\n"), cmdname, path);
6164 return (1);
6165 }
6166
6167 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6168 ZFS_TYPE_FILESYSTEM)) == NULL)
6169 return (1);
6170
6171 ret = 1;
6172 if (stat64(entry.mnt_mountp, &statbuf) != 0) {
6173 (void) fprintf(stderr, gettext("cannot %s '%s': %s\n"),
6174 cmdname, path, strerror(errno));
6175 goto out;
6176 } else if (statbuf.st_ino != path_inode) {
6177 (void) fprintf(stderr, gettext("cannot "
6178 "%s '%s': not a mountpoint\n"), cmdname, path);
6179 goto out;
6180 }
6181
6182 if (op == OP_SHARE) {
6183 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6184 char smbshare_prop[ZFS_MAXPROPLEN];
6185
6186 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS, nfs_mnt_prop,
6187 sizeof (nfs_mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
6188 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB, smbshare_prop,
6189 sizeof (smbshare_prop), NULL, NULL, 0, B_FALSE) == 0);
6190
6191 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6192 strcmp(smbshare_prop, "off") == 0) {
6193 (void) fprintf(stderr, gettext("cannot unshare "
6194 "'%s': legacy share\n"), path);
6195 (void) fprintf(stderr, gettext("use exportfs(8) "
6196 "or smbcontrol(1) to unshare this filesystem\n"));
6197 } else if (!zfs_is_shared(zhp)) {
6198 (void) fprintf(stderr, gettext("cannot unshare '%s': "
6199 "not currently shared\n"), path);
6200 } else {
6201 ret = zfs_unshareall_bypath(zhp, path);
6202 }
6203 } else {
6204 char mtpt_prop[ZFS_MAXPROPLEN];
6205
6206 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT, mtpt_prop,
6207 sizeof (mtpt_prop), NULL, NULL, 0, B_FALSE) == 0);
6208
6209 if (is_manual) {
6210 ret = zfs_unmount(zhp, NULL, flags);
6211 } else if (strcmp(mtpt_prop, "legacy") == 0) {
6212 (void) fprintf(stderr, gettext("cannot unmount "
6213 "'%s': legacy mountpoint\n"),
6214 zfs_get_name(zhp));
6215 (void) fprintf(stderr, gettext("use umount(8) "
6216 "to unmount this filesystem\n"));
6217 } else {
6218 ret = zfs_unmountall(zhp, flags);
6219 }
6220 }
6221
6222 out:
6223 zfs_close(zhp);
6224
6225 return (ret != 0);
6226 }
6227
6228 /*
6229 * Generic callback for unsharing or unmounting a filesystem.
6230 */
6231 static int
6232 unshare_unmount(int op, int argc, char **argv)
6233 {
6234 int do_all = 0;
6235 int flags = 0;
6236 int ret = 0;
6237 int c;
6238 zfs_handle_t *zhp;
6239 char nfs_mnt_prop[ZFS_MAXPROPLEN];
6240 char sharesmb[ZFS_MAXPROPLEN];
6241
6242 /* check options */
6243 while ((c = getopt(argc, argv, op == OP_SHARE ? "a" : "af")) != -1) {
6244 switch (c) {
6245 case 'a':
6246 do_all = 1;
6247 break;
6248 case 'f':
6249 flags = MS_FORCE;
6250 break;
6251 case '?':
6252 (void) fprintf(stderr, gettext("invalid option '%c'\n"),
6253 optopt);
6254 usage(B_FALSE);
6255 }
6256 }
6257
6258 argc -= optind;
6259 argv += optind;
6260
6261 if (do_all) {
6262 /*
6263 * We could make use of zfs_for_each() to walk all datasets in
6264 * the system, but this would be very inefficient, especially
6265 * since we would have to linearly search /etc/mtab for each
6266 * one. Instead, do one pass through /etc/mtab looking for
6267 * zfs entries and call zfs_unmount() for each one.
6268 *
6269 * Things get a little tricky if the administrator has created
6270 * mountpoints beneath other ZFS filesystems. In this case, we
6271 * have to unmount the deepest filesystems first. To accomplish
6272 * this, we place all the mountpoints in an AVL tree sorted by
6273 * the special type (dataset name), and walk the result in
6274 * reverse to make sure to get any snapshots first.
6275 */
6276 struct mnttab entry;
6277 uu_avl_pool_t *pool;
6278 uu_avl_t *tree = NULL;
6279 unshare_unmount_node_t *node;
6280 uu_avl_index_t idx;
6281 uu_avl_walk_t *walk;
6282
6283 if (argc != 0) {
6284 (void) fprintf(stderr, gettext("too many arguments\n"));
6285 usage(B_FALSE);
6286 }
6287
6288 if (((pool = uu_avl_pool_create("unmount_pool",
6289 sizeof (unshare_unmount_node_t),
6290 offsetof(unshare_unmount_node_t, un_avlnode),
6291 unshare_unmount_compare, UU_DEFAULT)) == NULL) ||
6292 ((tree = uu_avl_create(pool, NULL, UU_DEFAULT)) == NULL))
6293 nomem();
6294
6295 /* Reopen MNTTAB to prevent reading stale data from open file */
6296 if (freopen(MNTTAB, "r", mnttab_file) == NULL)
6297 return (ENOENT);
6298
6299 while (getmntent(mnttab_file, &entry) == 0) {
6300
6301 /* ignore non-ZFS entries */
6302 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
6303 continue;
6304
6305 /* ignore snapshots */
6306 if (strchr(entry.mnt_special, '@') != NULL)
6307 continue;
6308
6309 if ((zhp = zfs_open(g_zfs, entry.mnt_special,
6310 ZFS_TYPE_FILESYSTEM)) == NULL) {
6311 ret = 1;
6312 continue;
6313 }
6314
6315 switch (op) {
6316 case OP_SHARE:
6317 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6318 nfs_mnt_prop,
6319 sizeof (nfs_mnt_prop),
6320 NULL, NULL, 0, B_FALSE) == 0);
6321 if (strcmp(nfs_mnt_prop, "off") != 0)
6322 break;
6323 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6324 nfs_mnt_prop,
6325 sizeof (nfs_mnt_prop),
6326 NULL, NULL, 0, B_FALSE) == 0);
6327 if (strcmp(nfs_mnt_prop, "off") == 0)
6328 continue;
6329 break;
6330 case OP_MOUNT:
6331 /* Ignore legacy mounts */
6332 verify(zfs_prop_get(zhp, ZFS_PROP_MOUNTPOINT,
6333 nfs_mnt_prop,
6334 sizeof (nfs_mnt_prop),
6335 NULL, NULL, 0, B_FALSE) == 0);
6336 if (strcmp(nfs_mnt_prop, "legacy") == 0)
6337 continue;
6338 /* Ignore canmount=noauto mounts */
6339 if (zfs_prop_get_int(zhp, ZFS_PROP_CANMOUNT) ==
6340 ZFS_CANMOUNT_NOAUTO)
6341 continue;
6342 default:
6343 break;
6344 }
6345
6346 node = safe_malloc(sizeof (unshare_unmount_node_t));
6347 node->un_zhp = zhp;
6348 node->un_mountp = safe_strdup(entry.mnt_mountp);
6349
6350 uu_avl_node_init(node, &node->un_avlnode, pool);
6351
6352 if (uu_avl_find(tree, node, NULL, &idx) == NULL) {
6353 uu_avl_insert(tree, node, idx);
6354 } else {
6355 zfs_close(node->un_zhp);
6356 free(node->un_mountp);
6357 free(node);
6358 }
6359 }
6360
6361 /*
6362 * Walk the AVL tree in reverse, unmounting each filesystem and
6363 * removing it from the AVL tree in the process.
6364 */
6365 if ((walk = uu_avl_walk_start(tree,
6366 UU_WALK_REVERSE | UU_WALK_ROBUST)) == NULL)
6367 nomem();
6368
6369 while ((node = uu_avl_walk_next(walk)) != NULL) {
6370 uu_avl_remove(tree, node);
6371
6372 switch (op) {
6373 case OP_SHARE:
6374 if (zfs_unshareall_bypath(node->un_zhp,
6375 node->un_mountp) != 0)
6376 ret = 1;
6377 break;
6378
6379 case OP_MOUNT:
6380 if (zfs_unmount(node->un_zhp,
6381 node->un_mountp, flags) != 0)
6382 ret = 1;
6383 break;
6384 }
6385
6386 zfs_close(node->un_zhp);
6387 free(node->un_mountp);
6388 free(node);
6389 }
6390
6391 uu_avl_walk_end(walk);
6392 uu_avl_destroy(tree);
6393 uu_avl_pool_destroy(pool);
6394
6395 } else {
6396 if (argc != 1) {
6397 if (argc == 0)
6398 (void) fprintf(stderr,
6399 gettext("missing filesystem argument\n"));
6400 else
6401 (void) fprintf(stderr,
6402 gettext("too many arguments\n"));
6403 usage(B_FALSE);
6404 }
6405
6406 /*
6407 * We have an argument, but it may be a full path or a ZFS
6408 * filesystem. Pass full paths off to unmount_path() (shared by
6409 * manual_unmount), otherwise open the filesystem and pass to
6410 * zfs_unmount().
6411 */
6412 if (argv[0][0] == '/')
6413 return (unshare_unmount_path(op, argv[0],
6414 flags, B_FALSE));
6415
6416 if ((zhp = zfs_open(g_zfs, argv[0],
6417 ZFS_TYPE_FILESYSTEM)) == NULL)
6418 return (1);
6419
6420 verify(zfs_prop_get(zhp, op == OP_SHARE ?
6421 ZFS_PROP_SHARENFS : ZFS_PROP_MOUNTPOINT,
6422 nfs_mnt_prop, sizeof (nfs_mnt_prop), NULL,
6423 NULL, 0, B_FALSE) == 0);
6424
6425 switch (op) {
6426 case OP_SHARE:
6427 verify(zfs_prop_get(zhp, ZFS_PROP_SHARENFS,
6428 nfs_mnt_prop,
6429 sizeof (nfs_mnt_prop),
6430 NULL, NULL, 0, B_FALSE) == 0);
6431 verify(zfs_prop_get(zhp, ZFS_PROP_SHARESMB,
6432 sharesmb, sizeof (sharesmb), NULL, NULL,
6433 0, B_FALSE) == 0);
6434
6435 if (strcmp(nfs_mnt_prop, "off") == 0 &&
6436 strcmp(sharesmb, "off") == 0) {
6437 (void) fprintf(stderr, gettext("cannot "
6438 "unshare '%s': legacy share\n"),
6439 zfs_get_name(zhp));
6440 (void) fprintf(stderr, gettext("use "
6441 "unshare(1M) to unshare this "
6442 "filesystem\n"));
6443 ret = 1;
6444 } else if (!zfs_is_shared(zhp)) {
6445 (void) fprintf(stderr, gettext("cannot "
6446 "unshare '%s': not currently "
6447 "shared\n"), zfs_get_name(zhp));
6448 ret = 1;
6449 } else if (zfs_unshareall(zhp) != 0) {
6450 ret = 1;
6451 }
6452 break;
6453
6454 case OP_MOUNT:
6455 if (strcmp(nfs_mnt_prop, "legacy") == 0) {
6456 (void) fprintf(stderr, gettext("cannot "
6457 "unmount '%s': legacy "
6458 "mountpoint\n"), zfs_get_name(zhp));
6459 (void) fprintf(stderr, gettext("use "
6460 "umount(1M) to unmount this "
6461 "filesystem\n"));
6462 ret = 1;
6463 } else if (!zfs_is_mounted(zhp, NULL)) {
6464 (void) fprintf(stderr, gettext("cannot "
6465 "unmount '%s': not currently "
6466 "mounted\n"),
6467 zfs_get_name(zhp));
6468 ret = 1;
6469 } else if (zfs_unmountall(zhp, flags) != 0) {
6470 ret = 1;
6471 }
6472 break;
6473 }
6474
6475 zfs_close(zhp);
6476 }
6477
6478 return (ret);
6479 }
6480
6481 /*
6482 * zfs unmount -a
6483 * zfs unmount filesystem
6484 *
6485 * Unmount all filesystems, or a specific ZFS filesystem.
6486 */
6487 static int
6488 zfs_do_unmount(int argc, char **argv)
6489 {
6490 return (unshare_unmount(OP_MOUNT, argc, argv));
6491 }
6492
6493 /*
6494 * zfs unshare -a
6495 * zfs unshare filesystem
6496 *
6497 * Unshare all filesystems, or a specific ZFS filesystem.
6498 */
6499 static int
6500 zfs_do_unshare(int argc, char **argv)
6501 {
6502 return (unshare_unmount(OP_SHARE, argc, argv));
6503 }
6504
6505 static int
6506 find_command_idx(char *command, int *idx)
6507 {
6508 int i;
6509
6510 for (i = 0; i < NCOMMAND; i++) {
6511 if (command_table[i].name == NULL)
6512 continue;
6513
6514 if (strcmp(command, command_table[i].name) == 0) {
6515 *idx = i;
6516 return (0);
6517 }
6518 }
6519 return (1);
6520 }
6521
6522 static int
6523 zfs_do_diff(int argc, char **argv)
6524 {
6525 zfs_handle_t *zhp;
6526 int flags = 0;
6527 char *tosnap = NULL;
6528 char *fromsnap = NULL;
6529 char *atp, *copy;
6530 int err = 0;
6531 int c;
6532
6533 while ((c = getopt(argc, argv, "FHt")) != -1) {
6534 switch (c) {
6535 case 'F':
6536 flags |= ZFS_DIFF_CLASSIFY;
6537 break;
6538 case 'H':
6539 flags |= ZFS_DIFF_PARSEABLE;
6540 break;
6541 case 't':
6542 flags |= ZFS_DIFF_TIMESTAMP;
6543 break;
6544 default:
6545 (void) fprintf(stderr,
6546 gettext("invalid option '%c'\n"), optopt);
6547 usage(B_FALSE);
6548 }
6549 }
6550
6551 argc -= optind;
6552 argv += optind;
6553
6554 if (argc < 1) {
6555 (void) fprintf(stderr,
6556 gettext("must provide at least one snapshot name\n"));
6557 usage(B_FALSE);
6558 }
6559
6560 if (argc > 2) {
6561 (void) fprintf(stderr, gettext("too many arguments\n"));
6562 usage(B_FALSE);
6563 }
6564
6565 fromsnap = argv[0];
6566 tosnap = (argc == 2) ? argv[1] : NULL;
6567
6568 copy = NULL;
6569 if (*fromsnap != '@')
6570 copy = strdup(fromsnap);
6571 else if (tosnap)
6572 copy = strdup(tosnap);
6573 if (copy == NULL)
6574 usage(B_FALSE);
6575
6576 if ((atp = strchr(copy, '@')))
6577 *atp = '\0';
6578
6579 if ((zhp = zfs_open(g_zfs, copy, ZFS_TYPE_FILESYSTEM)) == NULL)
6580 return (1);
6581
6582 free(copy);
6583
6584 /*
6585 * Ignore SIGPIPE so that the library can give us
6586 * information on any failure
6587 */
6588 (void) sigignore(SIGPIPE);
6589
6590 err = zfs_show_diffs(zhp, STDOUT_FILENO, fromsnap, tosnap, flags);
6591
6592 zfs_close(zhp);
6593
6594 return (err != 0);
6595 }
6596
6597 /*
6598 * zfs bookmark <fs@snap> <fs#bmark>
6599 *
6600 * Creates a bookmark with the given name from the given snapshot.
6601 */
6602 static int
6603 zfs_do_bookmark(int argc, char **argv)
6604 {
6605 char snapname[ZFS_MAXNAMELEN];
6606 zfs_handle_t *zhp;
6607 nvlist_t *nvl;
6608 int ret = 0;
6609 int c;
6610
6611 /* check options */
6612 while ((c = getopt(argc, argv, "")) != -1) {
6613 switch (c) {
6614 case '?':
6615 (void) fprintf(stderr,
6616 gettext("invalid option '%c'\n"), optopt);
6617 goto usage;
6618 }
6619 }
6620
6621 argc -= optind;
6622 argv += optind;
6623
6624 /* check number of arguments */
6625 if (argc < 1) {
6626 (void) fprintf(stderr, gettext("missing snapshot argument\n"));
6627 goto usage;
6628 }
6629 if (argc < 2) {
6630 (void) fprintf(stderr, gettext("missing bookmark argument\n"));
6631 goto usage;
6632 }
6633
6634 if (strchr(argv[1], '#') == NULL) {
6635 (void) fprintf(stderr,
6636 gettext("invalid bookmark name '%s' -- "
6637 "must contain a '#'\n"), argv[1]);
6638 goto usage;
6639 }
6640
6641 if (argv[0][0] == '@') {
6642 /*
6643 * Snapshot name begins with @.
6644 * Default to same fs as bookmark.
6645 */
6646 (void) strncpy(snapname, argv[1], sizeof (snapname));
6647 *strchr(snapname, '#') = '\0';
6648 (void) strlcat(snapname, argv[0], sizeof (snapname));
6649 } else {
6650 (void) strncpy(snapname, argv[0], sizeof (snapname));
6651 }
6652 zhp = zfs_open(g_zfs, snapname, ZFS_TYPE_SNAPSHOT);
6653 if (zhp == NULL)
6654 goto usage;
6655 zfs_close(zhp);
6656
6657
6658 nvl = fnvlist_alloc();
6659 fnvlist_add_string(nvl, argv[1], snapname);
6660 ret = lzc_bookmark(nvl, NULL);
6661 fnvlist_free(nvl);
6662
6663 if (ret != 0) {
6664 const char *err_msg;
6665 char errbuf[1024];
6666
6667 (void) snprintf(errbuf, sizeof (errbuf),
6668 dgettext(TEXT_DOMAIN,
6669 "cannot create bookmark '%s'"), argv[1]);
6670
6671 switch (ret) {
6672 case EXDEV:
6673 err_msg = "bookmark is in a different pool";
6674 break;
6675 case EEXIST:
6676 err_msg = "bookmark exists";
6677 break;
6678 case EINVAL:
6679 err_msg = "invalid argument";
6680 break;
6681 case ENOTSUP:
6682 err_msg = "bookmark feature not enabled";
6683 break;
6684 case ENOSPC:
6685 err_msg = "out of space";
6686 break;
6687 default:
6688 err_msg = "unknown error";
6689 break;
6690 }
6691 (void) fprintf(stderr, "%s: %s\n", errbuf,
6692 dgettext(TEXT_DOMAIN, err_msg));
6693 }
6694
6695 return (ret != 0);
6696
6697 usage:
6698 usage(B_FALSE);
6699 return (-1);
6700 }
6701
6702 int
6703 main(int argc, char **argv)
6704 {
6705 int ret = 0;
6706 int i = 0;
6707 char *cmdname;
6708
6709 (void) setlocale(LC_ALL, "");
6710 (void) textdomain(TEXT_DOMAIN);
6711
6712 dprintf_setup(&argc, argv);
6713
6714 opterr = 0;
6715
6716 /*
6717 * Make sure the user has specified some command.
6718 */
6719 if (argc < 2) {
6720 (void) fprintf(stderr, gettext("missing command\n"));
6721 usage(B_FALSE);
6722 }
6723
6724 cmdname = argv[1];
6725
6726 /*
6727 * The 'umount' command is an alias for 'unmount'
6728 */
6729 if (strcmp(cmdname, "umount") == 0)
6730 cmdname = "unmount";
6731
6732 /*
6733 * The 'recv' command is an alias for 'receive'
6734 */
6735 if (strcmp(cmdname, "recv") == 0)
6736 cmdname = "receive";
6737
6738 /*
6739 * The 'snap' command is an alias for 'snapshot'
6740 */
6741 if (strcmp(cmdname, "snap") == 0)
6742 cmdname = "snapshot";
6743
6744 /*
6745 * Special case '-?'
6746 */
6747 if ((strcmp(cmdname, "-?") == 0) ||
6748 (strcmp(cmdname, "--help") == 0))
6749 usage(B_TRUE);
6750
6751 if ((g_zfs = libzfs_init()) == NULL) {
6752 (void) fprintf(stderr, "%s", libzfs_error_init(errno));
6753 return (1);
6754 }
6755
6756 mnttab_file = g_zfs->libzfs_mnttab;
6757
6758 zfs_save_arguments(argc, argv, history_str, sizeof (history_str));
6759
6760 libzfs_print_on_error(g_zfs, B_TRUE);
6761
6762 /*
6763 * Run the appropriate command.
6764 */
6765 libzfs_mnttab_cache(g_zfs, B_TRUE);
6766 if (find_command_idx(cmdname, &i) == 0) {
6767 current_command = &command_table[i];
6768 ret = command_table[i].func(argc - 1, argv + 1);
6769 } else if (strchr(cmdname, '=') != NULL) {
6770 verify(find_command_idx("set", &i) == 0);
6771 current_command = &command_table[i];
6772 ret = command_table[i].func(argc, argv);
6773 } else {
6774 (void) fprintf(stderr, gettext("unrecognized "
6775 "command '%s'\n"), cmdname);
6776 usage(B_FALSE);
6777 ret = 1;
6778 }
6779
6780 if (ret == 0 && log_history)
6781 (void) zpool_log_history(g_zfs, history_str);
6782
6783 libzfs_fini(g_zfs);
6784
6785 /*
6786 * The 'ZFS_ABORT' environment variable causes us to dump core on exit
6787 * for the purposes of running ::findleaks.
6788 */
6789 if (getenv("ZFS_ABORT") != NULL) {
6790 (void) printf("dumping core by request\n");
6791 abort();
6792 }
6793
6794 return (ret);
6795 }