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