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