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