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