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