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