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