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