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