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