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