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