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