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