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