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