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