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