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