]> git.proxmox.com Git - mirror_zfs-debian.git/blob - lib/libzfs/libzfs_util.c
Imported Upstream version 0.6.5.6
[mirror_zfs-debian.git] / lib / libzfs / libzfs_util.c
1 /*
2 * CDDL HEADER START
3 *
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
7 *
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
12 *
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
18 *
19 * CDDL HEADER END
20 */
21
22 /*
23 * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24 * Copyright (c) 2013, Joyent, Inc. All rights reserved.
25 * Copyright (c) 2012 by Delphix. All rights reserved.
26 */
27
28 /*
29 * Internal utility routines for the ZFS library.
30 */
31
32 #include <errno.h>
33 #include <fcntl.h>
34 #include <libintl.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <strings.h>
39 #include <unistd.h>
40 #include <ctype.h>
41 #include <math.h>
42 #include <sys/stat.h>
43 #include <sys/mnttab.h>
44 #include <sys/mntent.h>
45 #include <sys/types.h>
46 #include <wait.h>
47
48 #include <libzfs.h>
49 #include <libzfs_core.h>
50
51 #include "libzfs_impl.h"
52 #include "zfs_prop.h"
53 #include "zfeature_common.h"
54
55 int
56 libzfs_errno(libzfs_handle_t *hdl)
57 {
58 return (hdl->libzfs_error);
59 }
60
61 const char *
62 libzfs_error_init(int error)
63 {
64 switch (error) {
65 case ENXIO:
66 return (dgettext(TEXT_DOMAIN, "The ZFS modules are not "
67 "loaded.\nTry running '/sbin/modprobe zfs' as root "
68 "to load them.\n"));
69 case ENOENT:
70 return (dgettext(TEXT_DOMAIN, "The /dev/zfs device is "
71 "missing and must be created.\nTry running 'udevadm "
72 "trigger' as root to create it.\n"));
73 case ENOEXEC:
74 return (dgettext(TEXT_DOMAIN, "The ZFS modules cannot be "
75 "auto-loaded.\nTry running '/sbin/modprobe zfs' as "
76 "root to manually load them.\n"));
77 case EACCES:
78 return (dgettext(TEXT_DOMAIN, "Permission denied the "
79 "ZFS utilities must be run as root.\n"));
80 default:
81 return (dgettext(TEXT_DOMAIN, "Failed to initialize the "
82 "libzfs library.\n"));
83 }
84 }
85
86 const char *
87 libzfs_error_action(libzfs_handle_t *hdl)
88 {
89 return (hdl->libzfs_action);
90 }
91
92 const char *
93 libzfs_error_description(libzfs_handle_t *hdl)
94 {
95 if (hdl->libzfs_desc[0] != '\0')
96 return (hdl->libzfs_desc);
97
98 switch (hdl->libzfs_error) {
99 case EZFS_NOMEM:
100 return (dgettext(TEXT_DOMAIN, "out of memory"));
101 case EZFS_BADPROP:
102 return (dgettext(TEXT_DOMAIN, "invalid property value"));
103 case EZFS_PROPREADONLY:
104 return (dgettext(TEXT_DOMAIN, "read-only property"));
105 case EZFS_PROPTYPE:
106 return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
107 "datasets of this type"));
108 case EZFS_PROPNONINHERIT:
109 return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
110 case EZFS_PROPSPACE:
111 return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
112 case EZFS_BADTYPE:
113 return (dgettext(TEXT_DOMAIN, "operation not applicable to "
114 "datasets of this type"));
115 case EZFS_BUSY:
116 return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
117 case EZFS_EXISTS:
118 return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
119 case EZFS_NOENT:
120 return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
121 case EZFS_BADSTREAM:
122 return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
123 case EZFS_DSREADONLY:
124 return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
125 case EZFS_VOLTOOBIG:
126 return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
127 "this system"));
128 case EZFS_INVALIDNAME:
129 return (dgettext(TEXT_DOMAIN, "invalid name"));
130 case EZFS_BADRESTORE:
131 return (dgettext(TEXT_DOMAIN, "unable to restore to "
132 "destination"));
133 case EZFS_BADBACKUP:
134 return (dgettext(TEXT_DOMAIN, "backup failed"));
135 case EZFS_BADTARGET:
136 return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
137 case EZFS_NODEVICE:
138 return (dgettext(TEXT_DOMAIN, "no such device in pool"));
139 case EZFS_BADDEV:
140 return (dgettext(TEXT_DOMAIN, "invalid device"));
141 case EZFS_NOREPLICAS:
142 return (dgettext(TEXT_DOMAIN, "no valid replicas"));
143 case EZFS_RESILVERING:
144 return (dgettext(TEXT_DOMAIN, "currently resilvering"));
145 case EZFS_BADVERSION:
146 return (dgettext(TEXT_DOMAIN, "unsupported version or "
147 "feature"));
148 case EZFS_POOLUNAVAIL:
149 return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
150 case EZFS_DEVOVERFLOW:
151 return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
152 case EZFS_BADPATH:
153 return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
154 case EZFS_CROSSTARGET:
155 return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
156 "pools"));
157 case EZFS_ZONED:
158 return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
159 case EZFS_MOUNTFAILED:
160 return (dgettext(TEXT_DOMAIN, "mount failed"));
161 case EZFS_UMOUNTFAILED:
162 return (dgettext(TEXT_DOMAIN, "umount failed"));
163 case EZFS_UNSHARENFSFAILED:
164 return (dgettext(TEXT_DOMAIN, "unshare(1M) failed"));
165 case EZFS_SHARENFSFAILED:
166 return (dgettext(TEXT_DOMAIN, "share(1M) failed"));
167 case EZFS_UNSHARESMBFAILED:
168 return (dgettext(TEXT_DOMAIN, "smb remove share failed"));
169 case EZFS_SHARESMBFAILED:
170 return (dgettext(TEXT_DOMAIN, "smb add share failed"));
171 case EZFS_PERM:
172 return (dgettext(TEXT_DOMAIN, "permission denied"));
173 case EZFS_NOSPC:
174 return (dgettext(TEXT_DOMAIN, "out of space"));
175 case EZFS_FAULT:
176 return (dgettext(TEXT_DOMAIN, "bad address"));
177 case EZFS_IO:
178 return (dgettext(TEXT_DOMAIN, "I/O error"));
179 case EZFS_INTR:
180 return (dgettext(TEXT_DOMAIN, "signal received"));
181 case EZFS_ISSPARE:
182 return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
183 "spare"));
184 case EZFS_INVALCONFIG:
185 return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
186 case EZFS_RECURSIVE:
187 return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
188 case EZFS_NOHISTORY:
189 return (dgettext(TEXT_DOMAIN, "no history available"));
190 case EZFS_POOLPROPS:
191 return (dgettext(TEXT_DOMAIN, "failed to retrieve "
192 "pool properties"));
193 case EZFS_POOL_NOTSUP:
194 return (dgettext(TEXT_DOMAIN, "operation not supported "
195 "on this type of pool"));
196 case EZFS_POOL_INVALARG:
197 return (dgettext(TEXT_DOMAIN, "invalid argument for "
198 "this pool operation"));
199 case EZFS_NAMETOOLONG:
200 return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
201 case EZFS_OPENFAILED:
202 return (dgettext(TEXT_DOMAIN, "open failed"));
203 case EZFS_NOCAP:
204 return (dgettext(TEXT_DOMAIN,
205 "disk capacity information could not be retrieved"));
206 case EZFS_LABELFAILED:
207 return (dgettext(TEXT_DOMAIN, "write of label failed"));
208 case EZFS_BADWHO:
209 return (dgettext(TEXT_DOMAIN, "invalid user/group"));
210 case EZFS_BADPERM:
211 return (dgettext(TEXT_DOMAIN, "invalid permission"));
212 case EZFS_BADPERMSET:
213 return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
214 case EZFS_NODELEGATION:
215 return (dgettext(TEXT_DOMAIN, "delegated administration is "
216 "disabled on pool"));
217 case EZFS_BADCACHE:
218 return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
219 case EZFS_ISL2CACHE:
220 return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
221 case EZFS_VDEVNOTSUP:
222 return (dgettext(TEXT_DOMAIN, "vdev specification is not "
223 "supported"));
224 case EZFS_NOTSUP:
225 return (dgettext(TEXT_DOMAIN, "operation not supported "
226 "on this dataset"));
227 case EZFS_ACTIVE_SPARE:
228 return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
229 "device"));
230 case EZFS_UNPLAYED_LOGS:
231 return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
232 "logs"));
233 case EZFS_REFTAG_RELE:
234 return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
235 case EZFS_REFTAG_HOLD:
236 return (dgettext(TEXT_DOMAIN, "tag already exists on this "
237 "dataset"));
238 case EZFS_TAGTOOLONG:
239 return (dgettext(TEXT_DOMAIN, "tag too long"));
240 case EZFS_PIPEFAILED:
241 return (dgettext(TEXT_DOMAIN, "pipe create failed"));
242 case EZFS_THREADCREATEFAILED:
243 return (dgettext(TEXT_DOMAIN, "thread create failed"));
244 case EZFS_POSTSPLIT_ONLINE:
245 return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
246 "into a new one"));
247 case EZFS_SCRUBBING:
248 return (dgettext(TEXT_DOMAIN, "currently scrubbing; "
249 "use 'zpool scrub -s' to cancel current scrub"));
250 case EZFS_NO_SCRUB:
251 return (dgettext(TEXT_DOMAIN, "there is no active scrub"));
252 case EZFS_DIFF:
253 return (dgettext(TEXT_DOMAIN, "unable to generate diffs"));
254 case EZFS_DIFFDATA:
255 return (dgettext(TEXT_DOMAIN, "invalid diff data"));
256 case EZFS_POOLREADONLY:
257 return (dgettext(TEXT_DOMAIN, "pool is read-only"));
258 case EZFS_UNKNOWN:
259 return (dgettext(TEXT_DOMAIN, "unknown error"));
260 default:
261 assert(hdl->libzfs_error == 0);
262 return (dgettext(TEXT_DOMAIN, "no error"));
263 }
264 }
265
266 /*PRINTFLIKE2*/
267 void
268 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
269 {
270 va_list ap;
271
272 va_start(ap, fmt);
273
274 (void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
275 fmt, ap);
276 hdl->libzfs_desc_active = 1;
277
278 va_end(ap);
279 }
280
281 static void
282 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
283 {
284 (void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
285 fmt, ap);
286 hdl->libzfs_error = error;
287
288 if (hdl->libzfs_desc_active)
289 hdl->libzfs_desc_active = 0;
290 else
291 hdl->libzfs_desc[0] = '\0';
292
293 if (hdl->libzfs_printerr) {
294 if (error == EZFS_UNKNOWN) {
295 (void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
296 "error: %s\n"), libzfs_error_description(hdl));
297 abort();
298 }
299
300 (void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
301 libzfs_error_description(hdl));
302 if (error == EZFS_NOMEM)
303 exit(1);
304 }
305 }
306
307 int
308 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
309 {
310 return (zfs_error_fmt(hdl, error, "%s", msg));
311 }
312
313 /*PRINTFLIKE3*/
314 int
315 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
316 {
317 va_list ap;
318
319 va_start(ap, fmt);
320
321 zfs_verror(hdl, error, fmt, ap);
322
323 va_end(ap);
324
325 return (-1);
326 }
327
328 static int
329 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
330 va_list ap)
331 {
332 switch (error) {
333 case EPERM:
334 case EACCES:
335 zfs_verror(hdl, EZFS_PERM, fmt, ap);
336 return (-1);
337
338 case ECANCELED:
339 zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
340 return (-1);
341
342 case EIO:
343 zfs_verror(hdl, EZFS_IO, fmt, ap);
344 return (-1);
345
346 case EFAULT:
347 zfs_verror(hdl, EZFS_FAULT, fmt, ap);
348 return (-1);
349
350 case EINTR:
351 zfs_verror(hdl, EZFS_INTR, fmt, ap);
352 return (-1);
353 }
354
355 return (0);
356 }
357
358 int
359 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
360 {
361 return (zfs_standard_error_fmt(hdl, error, "%s", msg));
362 }
363
364 /*PRINTFLIKE3*/
365 int
366 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
367 {
368 va_list ap;
369
370 va_start(ap, fmt);
371
372 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
373 va_end(ap);
374 return (-1);
375 }
376
377 switch (error) {
378 case ENXIO:
379 case ENODEV:
380 case EPIPE:
381 zfs_verror(hdl, EZFS_IO, fmt, ap);
382 break;
383
384 case ENOENT:
385 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
386 "dataset does not exist"));
387 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
388 break;
389
390 case ENOSPC:
391 case EDQUOT:
392 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
393 return (-1);
394
395 case EEXIST:
396 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
397 "dataset already exists"));
398 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
399 break;
400
401 case EBUSY:
402 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
403 "dataset is busy"));
404 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
405 break;
406 case EROFS:
407 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
408 break;
409 case ENAMETOOLONG:
410 zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
411 break;
412 case ENOTSUP:
413 zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
414 break;
415 case EAGAIN:
416 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
417 "pool I/O is currently suspended"));
418 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
419 break;
420 default:
421 zfs_error_aux(hdl, strerror(error));
422 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
423 break;
424 }
425
426 va_end(ap);
427 return (-1);
428 }
429
430 int
431 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
432 {
433 return (zpool_standard_error_fmt(hdl, error, "%s", msg));
434 }
435
436 /*PRINTFLIKE3*/
437 int
438 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
439 {
440 va_list ap;
441
442 va_start(ap, fmt);
443
444 if (zfs_common_error(hdl, error, fmt, ap) != 0) {
445 va_end(ap);
446 return (-1);
447 }
448
449 switch (error) {
450 case ENODEV:
451 zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
452 break;
453
454 case ENOENT:
455 zfs_error_aux(hdl,
456 dgettext(TEXT_DOMAIN, "no such pool or dataset"));
457 zfs_verror(hdl, EZFS_NOENT, fmt, ap);
458 break;
459
460 case EEXIST:
461 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
462 "pool already exists"));
463 zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
464 break;
465
466 case EBUSY:
467 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
468 zfs_verror(hdl, EZFS_BUSY, fmt, ap);
469 break;
470
471 case ENXIO:
472 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
473 "one or more devices is currently unavailable"));
474 zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
475 break;
476
477 case ENAMETOOLONG:
478 zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
479 break;
480
481 case ENOTSUP:
482 zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
483 break;
484
485 case EINVAL:
486 zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
487 break;
488
489 case ENOSPC:
490 case EDQUOT:
491 zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
492 return (-1);
493
494 case EAGAIN:
495 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
496 "pool I/O is currently suspended"));
497 zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
498 break;
499
500 case EROFS:
501 zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
502 break;
503
504 default:
505 zfs_error_aux(hdl, strerror(error));
506 zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
507 }
508
509 va_end(ap);
510 return (-1);
511 }
512
513 /*
514 * Display an out of memory error message and abort the current program.
515 */
516 int
517 no_memory(libzfs_handle_t *hdl)
518 {
519 return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
520 }
521
522 /*
523 * A safe form of malloc() which will die if the allocation fails.
524 */
525 void *
526 zfs_alloc(libzfs_handle_t *hdl, size_t size)
527 {
528 void *data;
529
530 if ((data = calloc(1, size)) == NULL)
531 (void) no_memory(hdl);
532
533 return (data);
534 }
535
536 /*
537 * A safe form of asprintf() which will die if the allocation fails.
538 */
539 /*PRINTFLIKE2*/
540 char *
541 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
542 {
543 va_list ap;
544 char *ret;
545 int err;
546
547 va_start(ap, fmt);
548
549 err = vasprintf(&ret, fmt, ap);
550
551 va_end(ap);
552
553 if (err < 0)
554 (void) no_memory(hdl);
555
556 return (ret);
557 }
558
559 /*
560 * A safe form of realloc(), which also zeroes newly allocated space.
561 */
562 void *
563 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
564 {
565 void *ret;
566
567 if ((ret = realloc(ptr, newsize)) == NULL) {
568 (void) no_memory(hdl);
569 return (NULL);
570 }
571
572 bzero((char *)ret + oldsize, (newsize - oldsize));
573 return (ret);
574 }
575
576 /*
577 * A safe form of strdup() which will die if the allocation fails.
578 */
579 char *
580 zfs_strdup(libzfs_handle_t *hdl, const char *str)
581 {
582 char *ret;
583
584 if ((ret = strdup(str)) == NULL)
585 (void) no_memory(hdl);
586
587 return (ret);
588 }
589
590 /*
591 * Convert a number to an appropriately human-readable output.
592 */
593 void
594 zfs_nicenum(uint64_t num, char *buf, size_t buflen)
595 {
596 uint64_t n = num;
597 int index = 0;
598 char u;
599
600 while (n >= 1024 && index < 6) {
601 n /= 1024;
602 index++;
603 }
604
605 u = " KMGTPE"[index];
606
607 if (index == 0) {
608 (void) snprintf(buf, buflen, "%llu", (u_longlong_t) n);
609 } else if ((num & ((1ULL << 10 * index) - 1)) == 0) {
610 /*
611 * If this is an even multiple of the base, always display
612 * without any decimal precision.
613 */
614 (void) snprintf(buf, buflen, "%llu%c", (u_longlong_t) n, u);
615 } else {
616 /*
617 * We want to choose a precision that reflects the best choice
618 * for fitting in 5 characters. This can get rather tricky when
619 * we have numbers that are very close to an order of magnitude.
620 * For example, when displaying 10239 (which is really 9.999K),
621 * we want only a single place of precision for 10.0K. We could
622 * develop some complex heuristics for this, but it's much
623 * easier just to try each combination in turn.
624 */
625 int i;
626 for (i = 2; i >= 0; i--) {
627 if (snprintf(buf, buflen, "%.*f%c", i,
628 (double)num / (1ULL << 10 * index), u) <= 5)
629 break;
630 }
631 }
632 }
633
634 void
635 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
636 {
637 hdl->libzfs_printerr = printerr;
638 }
639
640 static int
641 libzfs_module_loaded(const char *module)
642 {
643 const char path_prefix[] = "/sys/module/";
644 char path[256];
645
646 memcpy(path, path_prefix, sizeof (path_prefix) - 1);
647 strcpy(path + sizeof (path_prefix) - 1, module);
648
649 return (access(path, F_OK) == 0);
650 }
651
652 int
653 libzfs_run_process(const char *path, char *argv[], int flags)
654 {
655 pid_t pid;
656 int error, devnull_fd;
657
658 pid = vfork();
659 if (pid == 0) {
660 devnull_fd = open("/dev/null", O_WRONLY);
661
662 if (devnull_fd < 0)
663 _exit(-1);
664
665 if (!(flags & STDOUT_VERBOSE))
666 (void) dup2(devnull_fd, STDOUT_FILENO);
667
668 if (!(flags & STDERR_VERBOSE))
669 (void) dup2(devnull_fd, STDERR_FILENO);
670
671 close(devnull_fd);
672
673 (void) execvp(path, argv);
674 _exit(-1);
675 } else if (pid > 0) {
676 int status;
677
678 while ((error = waitpid(pid, &status, 0)) == -1 &&
679 errno == EINTR);
680 if (error < 0 || !WIFEXITED(status))
681 return (-1);
682
683 return (WEXITSTATUS(status));
684 }
685
686 return (-1);
687 }
688
689 /*
690 * Verify the required ZFS_DEV device is available and optionally attempt
691 * to load the ZFS modules. Under normal circumstances the modules
692 * should already have been loaded by some external mechanism.
693 *
694 * Environment variables:
695 * - ZFS_MODULE_LOADING="YES|yes|ON|on" - Attempt to load modules.
696 * - ZFS_MODULE_TIMEOUT="<seconds>" - Seconds to wait for ZFS_DEV
697 */
698 static int
699 libzfs_load_module(const char *module)
700 {
701 char *argv[4] = {"/sbin/modprobe", "-q", (char *)module, (char *)0};
702 char *load_str, *timeout_str;
703 long timeout = 10; /* seconds */
704 long busy_timeout = 10; /* milliseconds */
705 int load = 0, fd;
706 hrtime_t start;
707
708 /* Optionally request module loading */
709 if (!libzfs_module_loaded(module)) {
710 load_str = getenv("ZFS_MODULE_LOADING");
711 if (load_str) {
712 if (!strncasecmp(load_str, "YES", strlen("YES")) ||
713 !strncasecmp(load_str, "ON", strlen("ON")))
714 load = 1;
715 else
716 load = 0;
717 }
718
719 if (load && libzfs_run_process("/sbin/modprobe", argv, 0))
720 return (ENOEXEC);
721 }
722
723 /* Module loading is synchronous it must be available */
724 if (!libzfs_module_loaded(module))
725 return (ENXIO);
726
727 /*
728 * Device creation by udev is asynchronous and waiting may be
729 * required. Busy wait for 10ms and then fall back to polling every
730 * 10ms for the allowed timeout (default 10s, max 10m). This is
731 * done to optimize for the common case where the device is
732 * immediately available and to avoid penalizing the possible
733 * case where udev is slow or unable to create the device.
734 */
735 timeout_str = getenv("ZFS_MODULE_TIMEOUT");
736 if (timeout_str) {
737 timeout = strtol(timeout_str, NULL, 0);
738 timeout = MAX(MIN(timeout, (10 * 60)), 0); /* 0 <= N <= 600 */
739 }
740
741 start = gethrtime();
742 do {
743 fd = open(ZFS_DEV, O_RDWR);
744 if (fd >= 0) {
745 (void) close(fd);
746 return (0);
747 } else if (errno != ENOENT) {
748 return (errno);
749 } else if (NSEC2MSEC(gethrtime() - start) < busy_timeout) {
750 sched_yield();
751 } else {
752 usleep(10 * MILLISEC);
753 }
754 } while (NSEC2MSEC(gethrtime() - start) < (timeout * MILLISEC));
755
756 return (ENOENT);
757 }
758
759 libzfs_handle_t *
760 libzfs_init(void)
761 {
762 libzfs_handle_t *hdl;
763 int error;
764
765 error = libzfs_load_module(ZFS_DRIVER);
766 if (error) {
767 errno = error;
768 return (NULL);
769 }
770
771 if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
772 return (NULL);
773 }
774
775 if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR)) < 0) {
776 free(hdl);
777 return (NULL);
778 }
779
780 #ifdef HAVE_SETMNTENT
781 if ((hdl->libzfs_mnttab = setmntent(MNTTAB, "r")) == NULL) {
782 #else
783 if ((hdl->libzfs_mnttab = fopen(MNTTAB, "r")) == NULL) {
784 #endif
785 (void) close(hdl->libzfs_fd);
786 free(hdl);
787 return (NULL);
788 }
789
790 hdl->libzfs_sharetab = fopen("/etc/dfs/sharetab", "r");
791
792 if (libzfs_core_init() != 0) {
793 (void) close(hdl->libzfs_fd);
794 (void) fclose(hdl->libzfs_mnttab);
795 (void) fclose(hdl->libzfs_sharetab);
796 free(hdl);
797 return (NULL);
798 }
799
800 zfs_prop_init();
801 zpool_prop_init();
802 zpool_feature_init();
803 libzfs_mnttab_init(hdl);
804
805 return (hdl);
806 }
807
808 void
809 libzfs_fini(libzfs_handle_t *hdl)
810 {
811 (void) close(hdl->libzfs_fd);
812 if (hdl->libzfs_mnttab)
813 #ifdef HAVE_SETMNTENT
814 (void) endmntent(hdl->libzfs_mnttab);
815 #else
816 (void) fclose(hdl->libzfs_mnttab);
817 #endif
818 if (hdl->libzfs_sharetab)
819 (void) fclose(hdl->libzfs_sharetab);
820 zfs_uninit_libshare(hdl);
821 zpool_free_handles(hdl);
822 libzfs_fru_clear(hdl, B_TRUE);
823 namespace_clear(hdl);
824 libzfs_mnttab_fini(hdl);
825 libzfs_core_fini();
826 free(hdl);
827 }
828
829 libzfs_handle_t *
830 zpool_get_handle(zpool_handle_t *zhp)
831 {
832 return (zhp->zpool_hdl);
833 }
834
835 libzfs_handle_t *
836 zfs_get_handle(zfs_handle_t *zhp)
837 {
838 return (zhp->zfs_hdl);
839 }
840
841 zpool_handle_t *
842 zfs_get_pool_handle(const zfs_handle_t *zhp)
843 {
844 return (zhp->zpool_hdl);
845 }
846
847 /*
848 * Given a name, determine whether or not it's a valid path
849 * (starts with '/' or "./"). If so, walk the mnttab trying
850 * to match the device number. If not, treat the path as an
851 * fs/vol/snap name.
852 */
853 zfs_handle_t *
854 zfs_path_to_zhandle(libzfs_handle_t *hdl, char *path, zfs_type_t argtype)
855 {
856 struct stat64 statbuf;
857 struct extmnttab entry;
858 int ret;
859
860 if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
861 /*
862 * It's not a valid path, assume it's a name of type 'argtype'.
863 */
864 return (zfs_open(hdl, path, argtype));
865 }
866
867 if (stat64(path, &statbuf) != 0) {
868 (void) fprintf(stderr, "%s: %s\n", path, strerror(errno));
869 return (NULL);
870 }
871
872 /* Reopen MNTTAB to prevent reading stale data from open file */
873 if (freopen(MNTTAB, "r", hdl->libzfs_mnttab) == NULL)
874 return (NULL);
875
876 while ((ret = getextmntent(hdl->libzfs_mnttab, &entry, 0)) == 0) {
877 if (makedevice(entry.mnt_major, entry.mnt_minor) ==
878 statbuf.st_dev) {
879 break;
880 }
881 }
882 if (ret != 0) {
883 return (NULL);
884 }
885
886 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
887 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
888 path);
889 return (NULL);
890 }
891
892 return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
893 }
894
895 /*
896 * Append partition suffix to an otherwise fully qualified device path.
897 * This is used to generate the name the full path as its stored in
898 * ZPOOL_CONFIG_PATH for whole disk devices. On success the new length
899 * of 'path' will be returned on error a negative value is returned.
900 */
901 int
902 zfs_append_partition(char *path, size_t max_len)
903 {
904 int len = strlen(path);
905
906 if (strncmp(path, UDISK_ROOT, strlen(UDISK_ROOT)) == 0) {
907 if (len + 6 >= max_len)
908 return (-1);
909
910 (void) strcat(path, "-part1");
911 len += 6;
912 } else {
913 if (len + 2 >= max_len)
914 return (-1);
915
916 if (isdigit(path[len-1])) {
917 (void) strcat(path, "p1");
918 len += 2;
919 } else {
920 (void) strcat(path, "1");
921 len += 1;
922 }
923 }
924
925 return (len);
926 }
927
928 /*
929 * Given a shorthand device name check if a file by that name exists in any
930 * of the 'zpool_default_import_path' or ZPOOL_IMPORT_PATH directories. If
931 * one is found, store its fully qualified path in the 'path' buffer passed
932 * by the caller and return 0, otherwise return an error.
933 */
934 int
935 zfs_resolve_shortname(const char *name, char *path, size_t len)
936 {
937 int i, error = -1;
938 char *dir, *env, *envdup;
939
940 env = getenv("ZPOOL_IMPORT_PATH");
941 errno = ENOENT;
942
943 if (env) {
944 envdup = strdup(env);
945 dir = strtok(envdup, ":");
946 while (dir && error) {
947 (void) snprintf(path, len, "%s/%s", dir, name);
948 error = access(path, F_OK);
949 dir = strtok(NULL, ":");
950 }
951 free(envdup);
952 } else {
953 for (i = 0; i < DEFAULT_IMPORT_PATH_SIZE && error < 0; i++) {
954 (void) snprintf(path, len, "%s/%s",
955 zpool_default_import_path[i], name);
956 error = access(path, F_OK);
957 }
958 }
959
960 return (error ? ENOENT : 0);
961 }
962
963 /*
964 * Given a shorthand device name look for a match against 'cmp_name'. This
965 * is done by checking all prefix expansions using either the default
966 * 'zpool_default_import_paths' or the ZPOOL_IMPORT_PATH environment
967 * variable. Proper partition suffixes will be appended if this is a
968 * whole disk. When a match is found 0 is returned otherwise ENOENT.
969 */
970 static int
971 zfs_strcmp_shortname(char *name, char *cmp_name, int wholedisk)
972 {
973 int path_len, cmp_len, i = 0, error = ENOENT;
974 char *dir, *env, *envdup = NULL;
975 char path_name[MAXPATHLEN];
976
977 cmp_len = strlen(cmp_name);
978 env = getenv("ZPOOL_IMPORT_PATH");
979
980 if (env) {
981 envdup = strdup(env);
982 dir = strtok(envdup, ":");
983 } else {
984 dir = zpool_default_import_path[i];
985 }
986
987 while (dir) {
988 /* Trim trailing directory slashes from ZPOOL_IMPORT_PATH */
989 while (dir[strlen(dir)-1] == '/')
990 dir[strlen(dir)-1] = '\0';
991
992 path_len = snprintf(path_name, MAXPATHLEN, "%s/%s", dir, name);
993 if (wholedisk)
994 path_len = zfs_append_partition(path_name, MAXPATHLEN);
995
996 if ((path_len == cmp_len) && strcmp(path_name, cmp_name) == 0) {
997 error = 0;
998 break;
999 }
1000
1001 if (env) {
1002 dir = strtok(NULL, ":");
1003 } else if (++i < DEFAULT_IMPORT_PATH_SIZE) {
1004 dir = zpool_default_import_path[i];
1005 } else {
1006 dir = NULL;
1007 }
1008 }
1009
1010 if (env)
1011 free(envdup);
1012
1013 return (error);
1014 }
1015
1016 /*
1017 * Given either a shorthand or fully qualified path name look for a match
1018 * against 'cmp'. The passed name will be expanded as needed for comparison
1019 * purposes and redundant slashes stripped to ensure an accurate match.
1020 */
1021 int
1022 zfs_strcmp_pathname(char *name, char *cmp, int wholedisk)
1023 {
1024 int path_len, cmp_len;
1025 char path_name[MAXPATHLEN];
1026 char cmp_name[MAXPATHLEN];
1027 char *dir, *dup;
1028
1029 /* Strip redundant slashes if one exists due to ZPOOL_IMPORT_PATH */
1030 memset(cmp_name, 0, MAXPATHLEN);
1031 dup = strdup(cmp);
1032 dir = strtok(dup, "/");
1033 while (dir) {
1034 strcat(cmp_name, "/");
1035 strcat(cmp_name, dir);
1036 dir = strtok(NULL, "/");
1037 }
1038 free(dup);
1039
1040 if (name[0] != '/')
1041 return (zfs_strcmp_shortname(name, cmp_name, wholedisk));
1042
1043 (void) strlcpy(path_name, name, MAXPATHLEN);
1044 path_len = strlen(path_name);
1045 cmp_len = strlen(cmp_name);
1046
1047 if (wholedisk) {
1048 path_len = zfs_append_partition(path_name, MAXPATHLEN);
1049 if (path_len == -1)
1050 return (ENOMEM);
1051 }
1052
1053 if ((path_len != cmp_len) || strcmp(path_name, cmp_name))
1054 return (ENOENT);
1055
1056 return (0);
1057 }
1058
1059 /*
1060 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1061 * an ioctl().
1062 */
1063 int
1064 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1065 {
1066 if (len == 0)
1067 len = 16 * 1024;
1068 zc->zc_nvlist_dst_size = len;
1069 if ((zc->zc_nvlist_dst = (uint64_t)(uintptr_t)
1070 zfs_alloc(hdl, zc->zc_nvlist_dst_size)) == 0)
1071 return (-1);
1072
1073 return (0);
1074 }
1075
1076 /*
1077 * Called when an ioctl() which returns an nvlist fails with ENOMEM. This will
1078 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1079 * filled in by the kernel to indicate the actual required size.
1080 */
1081 int
1082 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1083 {
1084 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1085 if ((zc->zc_nvlist_dst = (uint64_t)(uintptr_t)
1086 zfs_alloc(hdl, zc->zc_nvlist_dst_size)) == 0)
1087 return (-1);
1088
1089 return (0);
1090 }
1091
1092 /*
1093 * Called to free the src and dst nvlists stored in the command structure.
1094 */
1095 void
1096 zcmd_free_nvlists(zfs_cmd_t *zc)
1097 {
1098 free((void *)(uintptr_t)zc->zc_nvlist_conf);
1099 free((void *)(uintptr_t)zc->zc_nvlist_src);
1100 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1101 }
1102
1103 static int
1104 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1105 nvlist_t *nvl)
1106 {
1107 char *packed;
1108 size_t len;
1109
1110 verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
1111
1112 if ((packed = zfs_alloc(hdl, len)) == NULL)
1113 return (-1);
1114
1115 verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1116
1117 *outnv = (uint64_t)(uintptr_t)packed;
1118 *outlen = len;
1119
1120 return (0);
1121 }
1122
1123 int
1124 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1125 {
1126 return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1127 &zc->zc_nvlist_conf_size, nvl));
1128 }
1129
1130 int
1131 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1132 {
1133 return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1134 &zc->zc_nvlist_src_size, nvl));
1135 }
1136
1137 /*
1138 * Unpacks an nvlist from the ZFS ioctl command structure.
1139 */
1140 int
1141 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1142 {
1143 if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1144 zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1145 return (no_memory(hdl));
1146
1147 return (0);
1148 }
1149
1150 int
1151 zfs_ioctl(libzfs_handle_t *hdl, int request, zfs_cmd_t *zc)
1152 {
1153 return (ioctl(hdl->libzfs_fd, request, zc));
1154 }
1155
1156 /*
1157 * ================================================================
1158 * API shared by zfs and zpool property management
1159 * ================================================================
1160 */
1161
1162 static void
1163 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1164 {
1165 zprop_list_t *pl = cbp->cb_proplist;
1166 int i;
1167 char *title;
1168 size_t len;
1169
1170 cbp->cb_first = B_FALSE;
1171 if (cbp->cb_scripted)
1172 return;
1173
1174 /*
1175 * Start with the length of the column headers.
1176 */
1177 cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1178 cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1179 "PROPERTY"));
1180 cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1181 "VALUE"));
1182 cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1183 "RECEIVED"));
1184 cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1185 "SOURCE"));
1186
1187 /* first property is always NAME */
1188 assert(cbp->cb_proplist->pl_prop ==
1189 ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME : ZFS_PROP_NAME));
1190
1191 /*
1192 * Go through and calculate the widths for each column. For the
1193 * 'source' column, we kludge it up by taking the worst-case scenario of
1194 * inheriting from the longest name. This is acceptable because in the
1195 * majority of cases 'SOURCE' is the last column displayed, and we don't
1196 * use the width anyway. Note that the 'VALUE' column can be oversized,
1197 * if the name of the property is much longer than any values we find.
1198 */
1199 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1200 /*
1201 * 'PROPERTY' column
1202 */
1203 if (pl->pl_prop != ZPROP_INVAL) {
1204 const char *propname = (type == ZFS_TYPE_POOL) ?
1205 zpool_prop_to_name(pl->pl_prop) :
1206 zfs_prop_to_name(pl->pl_prop);
1207
1208 len = strlen(propname);
1209 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1210 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1211 } else {
1212 len = strlen(pl->pl_user_prop);
1213 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1214 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1215 }
1216
1217 /*
1218 * 'VALUE' column. The first property is always the 'name'
1219 * property that was tacked on either by /sbin/zfs's
1220 * zfs_do_get() or when calling zprop_expand_list(), so we
1221 * ignore its width. If the user specified the name property
1222 * to display, then it will be later in the list in any case.
1223 */
1224 if (pl != cbp->cb_proplist &&
1225 pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1226 cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1227
1228 /* 'RECEIVED' column. */
1229 if (pl != cbp->cb_proplist &&
1230 pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1231 cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1232
1233 /*
1234 * 'NAME' and 'SOURCE' columns
1235 */
1236 if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
1237 ZFS_PROP_NAME) &&
1238 pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
1239 cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1240 cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1241 strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1242 }
1243 }
1244
1245 /*
1246 * Now go through and print the headers.
1247 */
1248 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1249 switch (cbp->cb_columns[i]) {
1250 case GET_COL_NAME:
1251 title = dgettext(TEXT_DOMAIN, "NAME");
1252 break;
1253 case GET_COL_PROPERTY:
1254 title = dgettext(TEXT_DOMAIN, "PROPERTY");
1255 break;
1256 case GET_COL_VALUE:
1257 title = dgettext(TEXT_DOMAIN, "VALUE");
1258 break;
1259 case GET_COL_RECVD:
1260 title = dgettext(TEXT_DOMAIN, "RECEIVED");
1261 break;
1262 case GET_COL_SOURCE:
1263 title = dgettext(TEXT_DOMAIN, "SOURCE");
1264 break;
1265 default:
1266 title = NULL;
1267 }
1268
1269 if (title != NULL) {
1270 if (i == (ZFS_GET_NCOLS - 1) ||
1271 cbp->cb_columns[i + 1] == GET_COL_NONE)
1272 (void) printf("%s", title);
1273 else
1274 (void) printf("%-*s ",
1275 cbp->cb_colwidths[cbp->cb_columns[i]],
1276 title);
1277 }
1278 }
1279 (void) printf("\n");
1280 }
1281
1282 /*
1283 * Display a single line of output, according to the settings in the callback
1284 * structure.
1285 */
1286 void
1287 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1288 const char *propname, const char *value, zprop_source_t sourcetype,
1289 const char *source, const char *recvd_value)
1290 {
1291 int i;
1292 const char *str = NULL;
1293 char buf[128];
1294
1295 /*
1296 * Ignore those source types that the user has chosen to ignore.
1297 */
1298 if ((sourcetype & cbp->cb_sources) == 0)
1299 return;
1300
1301 if (cbp->cb_first)
1302 zprop_print_headers(cbp, cbp->cb_type);
1303
1304 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1305 switch (cbp->cb_columns[i]) {
1306 case GET_COL_NAME:
1307 str = name;
1308 break;
1309
1310 case GET_COL_PROPERTY:
1311 str = propname;
1312 break;
1313
1314 case GET_COL_VALUE:
1315 str = value;
1316 break;
1317
1318 case GET_COL_SOURCE:
1319 switch (sourcetype) {
1320 case ZPROP_SRC_NONE:
1321 str = "-";
1322 break;
1323
1324 case ZPROP_SRC_DEFAULT:
1325 str = "default";
1326 break;
1327
1328 case ZPROP_SRC_LOCAL:
1329 str = "local";
1330 break;
1331
1332 case ZPROP_SRC_TEMPORARY:
1333 str = "temporary";
1334 break;
1335
1336 case ZPROP_SRC_INHERITED:
1337 (void) snprintf(buf, sizeof (buf),
1338 "inherited from %s", source);
1339 str = buf;
1340 break;
1341 case ZPROP_SRC_RECEIVED:
1342 str = "received";
1343 break;
1344 }
1345 break;
1346
1347 case GET_COL_RECVD:
1348 str = (recvd_value == NULL ? "-" : recvd_value);
1349 break;
1350
1351 default:
1352 continue;
1353 }
1354
1355 if (cbp->cb_columns[i + 1] == GET_COL_NONE)
1356 (void) printf("%s", str);
1357 else if (cbp->cb_scripted)
1358 (void) printf("%s\t", str);
1359 else
1360 (void) printf("%-*s ",
1361 cbp->cb_colwidths[cbp->cb_columns[i]],
1362 str);
1363 }
1364
1365 (void) printf("\n");
1366 }
1367
1368 /*
1369 * Given a numeric suffix, convert the value into a number of bits that the
1370 * resulting value must be shifted.
1371 */
1372 static int
1373 str2shift(libzfs_handle_t *hdl, const char *buf)
1374 {
1375 const char *ends = "BKMGTPEZ";
1376 int i;
1377
1378 if (buf[0] == '\0')
1379 return (0);
1380 for (i = 0; i < strlen(ends); i++) {
1381 if (toupper(buf[0]) == ends[i])
1382 break;
1383 }
1384 if (i == strlen(ends)) {
1385 if (hdl)
1386 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1387 "invalid numeric suffix '%s'"), buf);
1388 return (-1);
1389 }
1390
1391 /*
1392 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1393 * However, 'BB' and 'BiB' are disallowed.
1394 */
1395 if (buf[1] == '\0' ||
1396 (toupper(buf[0]) != 'B' &&
1397 ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1398 (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1399 buf[3] == '\0'))))
1400 return (10 * i);
1401
1402 if (hdl)
1403 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1404 "invalid numeric suffix '%s'"), buf);
1405 return (-1);
1406 }
1407
1408 /*
1409 * Convert a string of the form '100G' into a real number. Used when setting
1410 * properties or creating a volume. 'buf' is used to place an extended error
1411 * message for the caller to use.
1412 */
1413 int
1414 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1415 {
1416 char *end;
1417 int shift;
1418
1419 *num = 0;
1420
1421 /* Check to see if this looks like a number. */
1422 if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1423 if (hdl)
1424 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1425 "bad numeric value '%s'"), value);
1426 return (-1);
1427 }
1428
1429 /* Rely on strtoull() to process the numeric portion. */
1430 errno = 0;
1431 *num = strtoull(value, &end, 10);
1432
1433 /*
1434 * Check for ERANGE, which indicates that the value is too large to fit
1435 * in a 64-bit value.
1436 */
1437 if (errno == ERANGE) {
1438 if (hdl)
1439 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1440 "numeric value is too large"));
1441 return (-1);
1442 }
1443
1444 /*
1445 * If we have a decimal value, then do the computation with floating
1446 * point arithmetic. Otherwise, use standard arithmetic.
1447 */
1448 if (*end == '.') {
1449 double fval = strtod(value, &end);
1450
1451 if ((shift = str2shift(hdl, end)) == -1)
1452 return (-1);
1453
1454 fval *= pow(2, shift);
1455
1456 if (fval > UINT64_MAX) {
1457 if (hdl)
1458 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1459 "numeric value is too large"));
1460 return (-1);
1461 }
1462
1463 *num = (uint64_t)fval;
1464 } else {
1465 if ((shift = str2shift(hdl, end)) == -1)
1466 return (-1);
1467
1468 /* Check for overflow */
1469 if (shift >= 64 || (*num << shift) >> shift != *num) {
1470 if (hdl)
1471 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1472 "numeric value is too large"));
1473 return (-1);
1474 }
1475
1476 *num <<= shift;
1477 }
1478
1479 return (0);
1480 }
1481
1482 /*
1483 * Given a propname=value nvpair to set, parse any numeric properties
1484 * (index, boolean, etc) if they are specified as strings and add the
1485 * resulting nvpair to the returned nvlist.
1486 *
1487 * At the DSL layer, all properties are either 64-bit numbers or strings.
1488 * We want the user to be able to ignore this fact and specify properties
1489 * as native values (numbers, for example) or as strings (to simplify
1490 * command line utilities). This also handles converting index types
1491 * (compression, checksum, etc) from strings to their on-disk index.
1492 */
1493 int
1494 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1495 zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1496 const char *errbuf)
1497 {
1498 data_type_t datatype = nvpair_type(elem);
1499 zprop_type_t proptype;
1500 const char *propname;
1501 char *value;
1502 boolean_t isnone = B_FALSE;
1503
1504 if (type == ZFS_TYPE_POOL) {
1505 proptype = zpool_prop_get_type(prop);
1506 propname = zpool_prop_to_name(prop);
1507 } else {
1508 proptype = zfs_prop_get_type(prop);
1509 propname = zfs_prop_to_name(prop);
1510 }
1511
1512 /*
1513 * Convert any properties to the internal DSL value types.
1514 */
1515 *svalp = NULL;
1516 *ivalp = 0;
1517
1518 switch (proptype) {
1519 case PROP_TYPE_STRING:
1520 if (datatype != DATA_TYPE_STRING) {
1521 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1522 "'%s' must be a string"), nvpair_name(elem));
1523 goto error;
1524 }
1525 (void) nvpair_value_string(elem, svalp);
1526 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1527 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1528 "'%s' is too long"), nvpair_name(elem));
1529 goto error;
1530 }
1531 break;
1532
1533 case PROP_TYPE_NUMBER:
1534 if (datatype == DATA_TYPE_STRING) {
1535 (void) nvpair_value_string(elem, &value);
1536 if (strcmp(value, "none") == 0) {
1537 isnone = B_TRUE;
1538 } else if (zfs_nicestrtonum(hdl, value, ivalp)
1539 != 0) {
1540 goto error;
1541 }
1542 } else if (datatype == DATA_TYPE_UINT64) {
1543 (void) nvpair_value_uint64(elem, ivalp);
1544 } else {
1545 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1546 "'%s' must be a number"), nvpair_name(elem));
1547 goto error;
1548 }
1549
1550 /*
1551 * Quota special: force 'none' and don't allow 0.
1552 */
1553 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1554 (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1555 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1556 "use 'none' to disable quota/refquota"));
1557 goto error;
1558 }
1559
1560 /*
1561 * Special handling for "*_limit=none". In this case it's not
1562 * 0 but UINT64_MAX.
1563 */
1564 if ((type & ZFS_TYPE_DATASET) && isnone &&
1565 (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1566 prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1567 *ivalp = UINT64_MAX;
1568 }
1569 break;
1570
1571 case PROP_TYPE_INDEX:
1572 if (datatype != DATA_TYPE_STRING) {
1573 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1574 "'%s' must be a string"), nvpair_name(elem));
1575 goto error;
1576 }
1577
1578 (void) nvpair_value_string(elem, &value);
1579
1580 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1581 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1582 "'%s' must be one of '%s'"), propname,
1583 zprop_values(prop, type));
1584 goto error;
1585 }
1586 break;
1587
1588 default:
1589 abort();
1590 }
1591
1592 /*
1593 * Add the result to our return set of properties.
1594 */
1595 if (*svalp != NULL) {
1596 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1597 (void) no_memory(hdl);
1598 return (-1);
1599 }
1600 } else {
1601 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1602 (void) no_memory(hdl);
1603 return (-1);
1604 }
1605 }
1606
1607 return (0);
1608 error:
1609 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1610 return (-1);
1611 }
1612
1613 static int
1614 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1615 zfs_type_t type)
1616 {
1617 int prop;
1618 zprop_list_t *entry;
1619
1620 prop = zprop_name_to_prop(propname, type);
1621
1622 if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1623 prop = ZPROP_INVAL;
1624
1625 /*
1626 * When no property table entry can be found, return failure if
1627 * this is a pool property or if this isn't a user-defined
1628 * dataset property,
1629 */
1630 if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1631 !zpool_prop_feature(propname) &&
1632 !zpool_prop_unsupported(propname)) ||
1633 (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1634 !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1635 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1636 "invalid property '%s'"), propname);
1637 return (zfs_error(hdl, EZFS_BADPROP,
1638 dgettext(TEXT_DOMAIN, "bad property list")));
1639 }
1640
1641 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1642 return (-1);
1643
1644 entry->pl_prop = prop;
1645 if (prop == ZPROP_INVAL) {
1646 if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1647 NULL) {
1648 free(entry);
1649 return (-1);
1650 }
1651 entry->pl_width = strlen(propname);
1652 } else {
1653 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1654 type);
1655 }
1656
1657 *listp = entry;
1658
1659 return (0);
1660 }
1661
1662 /*
1663 * Given a comma-separated list of properties, construct a property list
1664 * containing both user-defined and native properties. This function will
1665 * return a NULL list if 'all' is specified, which can later be expanded
1666 * by zprop_expand_list().
1667 */
1668 int
1669 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1670 zfs_type_t type)
1671 {
1672 *listp = NULL;
1673
1674 /*
1675 * If 'all' is specified, return a NULL list.
1676 */
1677 if (strcmp(props, "all") == 0)
1678 return (0);
1679
1680 /*
1681 * If no props were specified, return an error.
1682 */
1683 if (props[0] == '\0') {
1684 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1685 "no properties specified"));
1686 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1687 "bad property list")));
1688 }
1689
1690 /*
1691 * It would be nice to use getsubopt() here, but the inclusion of column
1692 * aliases makes this more effort than it's worth.
1693 */
1694 while (*props != '\0') {
1695 size_t len;
1696 char *p;
1697 char c;
1698
1699 if ((p = strchr(props, ',')) == NULL) {
1700 len = strlen(props);
1701 p = props + len;
1702 } else {
1703 len = p - props;
1704 }
1705
1706 /*
1707 * Check for empty options.
1708 */
1709 if (len == 0) {
1710 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1711 "empty property name"));
1712 return (zfs_error(hdl, EZFS_BADPROP,
1713 dgettext(TEXT_DOMAIN, "bad property list")));
1714 }
1715
1716 /*
1717 * Check all regular property names.
1718 */
1719 c = props[len];
1720 props[len] = '\0';
1721
1722 if (strcmp(props, "space") == 0) {
1723 static char *spaceprops[] = {
1724 "name", "avail", "used", "usedbysnapshots",
1725 "usedbydataset", "usedbyrefreservation",
1726 "usedbychildren", NULL
1727 };
1728 int i;
1729
1730 for (i = 0; spaceprops[i]; i++) {
1731 if (addlist(hdl, spaceprops[i], listp, type))
1732 return (-1);
1733 listp = &(*listp)->pl_next;
1734 }
1735 } else {
1736 if (addlist(hdl, props, listp, type))
1737 return (-1);
1738 listp = &(*listp)->pl_next;
1739 }
1740
1741 props = p;
1742 if (c == ',')
1743 props++;
1744 }
1745
1746 return (0);
1747 }
1748
1749 void
1750 zprop_free_list(zprop_list_t *pl)
1751 {
1752 zprop_list_t *next;
1753
1754 while (pl != NULL) {
1755 next = pl->pl_next;
1756 free(pl->pl_user_prop);
1757 free(pl);
1758 pl = next;
1759 }
1760 }
1761
1762 typedef struct expand_data {
1763 zprop_list_t **last;
1764 libzfs_handle_t *hdl;
1765 zfs_type_t type;
1766 } expand_data_t;
1767
1768 int
1769 zprop_expand_list_cb(int prop, void *cb)
1770 {
1771 zprop_list_t *entry;
1772 expand_data_t *edp = cb;
1773
1774 if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
1775 return (ZPROP_INVAL);
1776
1777 entry->pl_prop = prop;
1778 entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1779 entry->pl_all = B_TRUE;
1780
1781 *(edp->last) = entry;
1782 edp->last = &entry->pl_next;
1783
1784 return (ZPROP_CONT);
1785 }
1786
1787 int
1788 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1789 {
1790 zprop_list_t *entry;
1791 zprop_list_t **last;
1792 expand_data_t exp;
1793
1794 if (*plp == NULL) {
1795 /*
1796 * If this is the very first time we've been called for an 'all'
1797 * specification, expand the list to include all native
1798 * properties.
1799 */
1800 last = plp;
1801
1802 exp.last = last;
1803 exp.hdl = hdl;
1804 exp.type = type;
1805
1806 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1807 B_FALSE, type) == ZPROP_INVAL)
1808 return (-1);
1809
1810 /*
1811 * Add 'name' to the beginning of the list, which is handled
1812 * specially.
1813 */
1814 if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1815 return (-1);
1816
1817 entry->pl_prop = (type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1818 ZFS_PROP_NAME;
1819 entry->pl_width = zprop_width(entry->pl_prop,
1820 &entry->pl_fixed, type);
1821 entry->pl_all = B_TRUE;
1822 entry->pl_next = *plp;
1823 *plp = entry;
1824 }
1825 return (0);
1826 }
1827
1828 int
1829 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1830 zfs_type_t type)
1831 {
1832 return (zprop_iter_common(func, cb, show_all, ordered, type));
1833 }