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