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