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