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