xref: /freebsd/sys/contrib/openzfs/lib/libzfs/libzfs_util.c (revision a50d73d5782a351ad83e8d1f84d11720a12e70d3)
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 https://opensource.org/licenses/CDDL-1.0.
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 2020 Joyent, Inc. All rights reserved.
25  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
26  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
27  * Copyright (c) 2017 Datto Inc.
28  * Copyright (c) 2020 The FreeBSD Foundation
29  *
30  * Portions of this software were developed by Allan Jude
31  * under sponsorship from the FreeBSD Foundation.
32  */
33 
34 /*
35  * Internal utility routines for the ZFS library.
36  */
37 
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <libintl.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <strings.h>
45 #include <unistd.h>
46 #include <math.h>
47 #if LIBFETCH_DYNAMIC
48 #include <dlfcn.h>
49 #endif
50 #include <sys/stat.h>
51 #include <sys/mnttab.h>
52 #include <sys/mntent.h>
53 #include <sys/types.h>
54 #include <sys/wait.h>
55 
56 #include <libzfs.h>
57 #include <libzfs_core.h>
58 
59 #include "libzfs_impl.h"
60 #include "zfs_prop.h"
61 #include "zfeature_common.h"
62 #include <zfs_fletcher.h>
63 #include <libzutil.h>
64 
65 /*
66  * We only care about the scheme in order to match the scheme
67  * with the handler. Each handler should validate the full URI
68  * as necessary.
69  */
70 #define	URI_REGEX	"^\\([A-Za-z][A-Za-z0-9+.\\-]*\\):"
71 
72 int
73 libzfs_errno(libzfs_handle_t *hdl)
74 {
75 	return (hdl->libzfs_error);
76 }
77 
78 const char *
79 libzfs_error_action(libzfs_handle_t *hdl)
80 {
81 	return (hdl->libzfs_action);
82 }
83 
84 const char *
85 libzfs_error_description(libzfs_handle_t *hdl)
86 {
87 	if (hdl->libzfs_desc[0] != '\0')
88 		return (hdl->libzfs_desc);
89 
90 	switch (hdl->libzfs_error) {
91 	case EZFS_NOMEM:
92 		return (dgettext(TEXT_DOMAIN, "out of memory"));
93 	case EZFS_BADPROP:
94 		return (dgettext(TEXT_DOMAIN, "invalid property value"));
95 	case EZFS_PROPREADONLY:
96 		return (dgettext(TEXT_DOMAIN, "read-only property"));
97 	case EZFS_PROPTYPE:
98 		return (dgettext(TEXT_DOMAIN, "property doesn't apply to "
99 		    "datasets of this type"));
100 	case EZFS_PROPNONINHERIT:
101 		return (dgettext(TEXT_DOMAIN, "property cannot be inherited"));
102 	case EZFS_PROPSPACE:
103 		return (dgettext(TEXT_DOMAIN, "invalid quota or reservation"));
104 	case EZFS_BADTYPE:
105 		return (dgettext(TEXT_DOMAIN, "operation not applicable to "
106 		    "datasets of this type"));
107 	case EZFS_BUSY:
108 		return (dgettext(TEXT_DOMAIN, "pool or dataset is busy"));
109 	case EZFS_EXISTS:
110 		return (dgettext(TEXT_DOMAIN, "pool or dataset exists"));
111 	case EZFS_NOENT:
112 		return (dgettext(TEXT_DOMAIN, "no such pool or dataset"));
113 	case EZFS_BADSTREAM:
114 		return (dgettext(TEXT_DOMAIN, "invalid backup stream"));
115 	case EZFS_DSREADONLY:
116 		return (dgettext(TEXT_DOMAIN, "dataset is read-only"));
117 	case EZFS_VOLTOOBIG:
118 		return (dgettext(TEXT_DOMAIN, "volume size exceeds limit for "
119 		    "this system"));
120 	case EZFS_INVALIDNAME:
121 		return (dgettext(TEXT_DOMAIN, "invalid name"));
122 	case EZFS_BADRESTORE:
123 		return (dgettext(TEXT_DOMAIN, "unable to restore to "
124 		    "destination"));
125 	case EZFS_BADBACKUP:
126 		return (dgettext(TEXT_DOMAIN, "backup failed"));
127 	case EZFS_BADTARGET:
128 		return (dgettext(TEXT_DOMAIN, "invalid target vdev"));
129 	case EZFS_NODEVICE:
130 		return (dgettext(TEXT_DOMAIN, "no such device in pool"));
131 	case EZFS_BADDEV:
132 		return (dgettext(TEXT_DOMAIN, "invalid device"));
133 	case EZFS_NOREPLICAS:
134 		return (dgettext(TEXT_DOMAIN, "no valid replicas"));
135 	case EZFS_RESILVERING:
136 		return (dgettext(TEXT_DOMAIN, "currently resilvering"));
137 	case EZFS_BADVERSION:
138 		return (dgettext(TEXT_DOMAIN, "unsupported version or "
139 		    "feature"));
140 	case EZFS_POOLUNAVAIL:
141 		return (dgettext(TEXT_DOMAIN, "pool is unavailable"));
142 	case EZFS_DEVOVERFLOW:
143 		return (dgettext(TEXT_DOMAIN, "too many devices in one vdev"));
144 	case EZFS_BADPATH:
145 		return (dgettext(TEXT_DOMAIN, "must be an absolute path"));
146 	case EZFS_CROSSTARGET:
147 		return (dgettext(TEXT_DOMAIN, "operation crosses datasets or "
148 		    "pools"));
149 	case EZFS_ZONED:
150 		return (dgettext(TEXT_DOMAIN, "dataset in use by local zone"));
151 	case EZFS_MOUNTFAILED:
152 		return (dgettext(TEXT_DOMAIN, "mount failed"));
153 	case EZFS_UMOUNTFAILED:
154 		return (dgettext(TEXT_DOMAIN, "unmount failed"));
155 	case EZFS_UNSHARENFSFAILED:
156 		return (dgettext(TEXT_DOMAIN, "NFS share removal failed"));
157 	case EZFS_SHARENFSFAILED:
158 		return (dgettext(TEXT_DOMAIN, "NFS share creation failed"));
159 	case EZFS_UNSHARESMBFAILED:
160 		return (dgettext(TEXT_DOMAIN, "SMB share removal failed"));
161 	case EZFS_SHARESMBFAILED:
162 		return (dgettext(TEXT_DOMAIN, "SMB share creation failed"));
163 	case EZFS_PERM:
164 		return (dgettext(TEXT_DOMAIN, "permission denied"));
165 	case EZFS_NOSPC:
166 		return (dgettext(TEXT_DOMAIN, "out of space"));
167 	case EZFS_FAULT:
168 		return (dgettext(TEXT_DOMAIN, "bad address"));
169 	case EZFS_IO:
170 		return (dgettext(TEXT_DOMAIN, "I/O error"));
171 	case EZFS_INTR:
172 		return (dgettext(TEXT_DOMAIN, "signal received"));
173 	case EZFS_CKSUM:
174 		return (dgettext(TEXT_DOMAIN, "insufficient replicas"));
175 	case EZFS_ISSPARE:
176 		return (dgettext(TEXT_DOMAIN, "device is reserved as a hot "
177 		    "spare"));
178 	case EZFS_INVALCONFIG:
179 		return (dgettext(TEXT_DOMAIN, "invalid vdev configuration"));
180 	case EZFS_RECURSIVE:
181 		return (dgettext(TEXT_DOMAIN, "recursive dataset dependency"));
182 	case EZFS_NOHISTORY:
183 		return (dgettext(TEXT_DOMAIN, "no history available"));
184 	case EZFS_POOLPROPS:
185 		return (dgettext(TEXT_DOMAIN, "failed to retrieve "
186 		    "pool properties"));
187 	case EZFS_POOL_NOTSUP:
188 		return (dgettext(TEXT_DOMAIN, "operation not supported "
189 		    "on this type of pool"));
190 	case EZFS_POOL_INVALARG:
191 		return (dgettext(TEXT_DOMAIN, "invalid argument for "
192 		    "this pool operation"));
193 	case EZFS_NAMETOOLONG:
194 		return (dgettext(TEXT_DOMAIN, "dataset name is too long"));
195 	case EZFS_OPENFAILED:
196 		return (dgettext(TEXT_DOMAIN, "open failed"));
197 	case EZFS_NOCAP:
198 		return (dgettext(TEXT_DOMAIN,
199 		    "disk capacity information could not be retrieved"));
200 	case EZFS_LABELFAILED:
201 		return (dgettext(TEXT_DOMAIN, "write of label failed"));
202 	case EZFS_BADWHO:
203 		return (dgettext(TEXT_DOMAIN, "invalid user/group"));
204 	case EZFS_BADPERM:
205 		return (dgettext(TEXT_DOMAIN, "invalid permission"));
206 	case EZFS_BADPERMSET:
207 		return (dgettext(TEXT_DOMAIN, "invalid permission set name"));
208 	case EZFS_NODELEGATION:
209 		return (dgettext(TEXT_DOMAIN, "delegated administration is "
210 		    "disabled on pool"));
211 	case EZFS_BADCACHE:
212 		return (dgettext(TEXT_DOMAIN, "invalid or missing cache file"));
213 	case EZFS_ISL2CACHE:
214 		return (dgettext(TEXT_DOMAIN, "device is in use as a cache"));
215 	case EZFS_VDEVNOTSUP:
216 		return (dgettext(TEXT_DOMAIN, "vdev specification is not "
217 		    "supported"));
218 	case EZFS_NOTSUP:
219 		return (dgettext(TEXT_DOMAIN, "operation not supported "
220 		    "on this dataset"));
221 	case EZFS_IOC_NOTSUPPORTED:
222 		return (dgettext(TEXT_DOMAIN, "operation not supported by "
223 		    "zfs kernel module"));
224 	case EZFS_ACTIVE_SPARE:
225 		return (dgettext(TEXT_DOMAIN, "pool has active shared spare "
226 		    "device"));
227 	case EZFS_UNPLAYED_LOGS:
228 		return (dgettext(TEXT_DOMAIN, "log device has unplayed intent "
229 		    "logs"));
230 	case EZFS_REFTAG_RELE:
231 		return (dgettext(TEXT_DOMAIN, "no such tag on this dataset"));
232 	case EZFS_REFTAG_HOLD:
233 		return (dgettext(TEXT_DOMAIN, "tag already exists on this "
234 		    "dataset"));
235 	case EZFS_TAGTOOLONG:
236 		return (dgettext(TEXT_DOMAIN, "tag too long"));
237 	case EZFS_PIPEFAILED:
238 		return (dgettext(TEXT_DOMAIN, "pipe create failed"));
239 	case EZFS_THREADCREATEFAILED:
240 		return (dgettext(TEXT_DOMAIN, "thread create failed"));
241 	case EZFS_POSTSPLIT_ONLINE:
242 		return (dgettext(TEXT_DOMAIN, "disk was split from this pool "
243 		    "into a new one"));
244 	case EZFS_SCRUB_PAUSED:
245 		return (dgettext(TEXT_DOMAIN, "scrub is paused; "
246 		    "use 'zpool scrub' to resume"));
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_NO_PENDING:
259 		return (dgettext(TEXT_DOMAIN, "operation is not "
260 		    "in progress"));
261 	case EZFS_CHECKPOINT_EXISTS:
262 		return (dgettext(TEXT_DOMAIN, "checkpoint exists"));
263 	case EZFS_DISCARDING_CHECKPOINT:
264 		return (dgettext(TEXT_DOMAIN, "currently discarding "
265 		    "checkpoint"));
266 	case EZFS_NO_CHECKPOINT:
267 		return (dgettext(TEXT_DOMAIN, "checkpoint does not exist"));
268 	case EZFS_DEVRM_IN_PROGRESS:
269 		return (dgettext(TEXT_DOMAIN, "device removal in progress"));
270 	case EZFS_VDEV_TOO_BIG:
271 		return (dgettext(TEXT_DOMAIN, "device exceeds supported size"));
272 	case EZFS_ACTIVE_POOL:
273 		return (dgettext(TEXT_DOMAIN, "pool is imported on a "
274 		    "different host"));
275 	case EZFS_CRYPTOFAILED:
276 		return (dgettext(TEXT_DOMAIN, "encryption failure"));
277 	case EZFS_TOOMANY:
278 		return (dgettext(TEXT_DOMAIN, "argument list too long"));
279 	case EZFS_INITIALIZING:
280 		return (dgettext(TEXT_DOMAIN, "currently initializing"));
281 	case EZFS_NO_INITIALIZE:
282 		return (dgettext(TEXT_DOMAIN, "there is no active "
283 		    "initialization"));
284 	case EZFS_WRONG_PARENT:
285 		return (dgettext(TEXT_DOMAIN, "invalid parent dataset"));
286 	case EZFS_TRIMMING:
287 		return (dgettext(TEXT_DOMAIN, "currently trimming"));
288 	case EZFS_NO_TRIM:
289 		return (dgettext(TEXT_DOMAIN, "there is no active trim"));
290 	case EZFS_TRIM_NOTSUP:
291 		return (dgettext(TEXT_DOMAIN, "trim operations are not "
292 		    "supported by this device"));
293 	case EZFS_NO_RESILVER_DEFER:
294 		return (dgettext(TEXT_DOMAIN, "this action requires the "
295 		    "resilver_defer feature"));
296 	case EZFS_EXPORT_IN_PROGRESS:
297 		return (dgettext(TEXT_DOMAIN, "pool export in progress"));
298 	case EZFS_REBUILDING:
299 		return (dgettext(TEXT_DOMAIN, "currently sequentially "
300 		    "resilvering"));
301 	case EZFS_VDEV_NOTSUP:
302 		return (dgettext(TEXT_DOMAIN, "operation not supported "
303 		    "on this type of vdev"));
304 	case EZFS_NOT_USER_NAMESPACE:
305 		return (dgettext(TEXT_DOMAIN, "the provided file "
306 		    "was not a user namespace file"));
307 	case EZFS_RESUME_EXISTS:
308 		return (dgettext(TEXT_DOMAIN, "Resuming recv on existing "
309 		    "dataset without force"));
310 	case EZFS_UNKNOWN:
311 		return (dgettext(TEXT_DOMAIN, "unknown error"));
312 	default:
313 		assert(hdl->libzfs_error == 0);
314 		return (dgettext(TEXT_DOMAIN, "no error"));
315 	}
316 }
317 
318 void
319 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
320 {
321 	va_list ap;
322 
323 	va_start(ap, fmt);
324 
325 	(void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
326 	    fmt, ap);
327 	hdl->libzfs_desc_active = 1;
328 
329 	va_end(ap);
330 }
331 
332 static void
333 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
334 {
335 	(void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
336 	    fmt, ap);
337 	hdl->libzfs_error = error;
338 
339 	if (hdl->libzfs_desc_active)
340 		hdl->libzfs_desc_active = 0;
341 	else
342 		hdl->libzfs_desc[0] = '\0';
343 
344 	if (hdl->libzfs_printerr) {
345 		if (error == EZFS_UNKNOWN) {
346 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
347 			    "error: %s: %s\n"), hdl->libzfs_action,
348 			    libzfs_error_description(hdl));
349 			abort();
350 		}
351 
352 		(void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
353 		    libzfs_error_description(hdl));
354 		if (error == EZFS_NOMEM)
355 			exit(1);
356 	}
357 }
358 
359 int
360 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
361 {
362 	return (zfs_error_fmt(hdl, error, "%s", msg));
363 }
364 
365 int
366 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
367 {
368 	va_list ap;
369 
370 	va_start(ap, fmt);
371 
372 	zfs_verror(hdl, error, fmt, ap);
373 
374 	va_end(ap);
375 
376 	return (-1);
377 }
378 
379 static int
380 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
381     va_list ap)
382 {
383 	switch (error) {
384 	case EPERM:
385 	case EACCES:
386 		zfs_verror(hdl, EZFS_PERM, fmt, ap);
387 		return (-1);
388 
389 	case ECANCELED:
390 		zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
391 		return (-1);
392 
393 	case EIO:
394 		zfs_verror(hdl, EZFS_IO, fmt, ap);
395 		return (-1);
396 
397 	case EFAULT:
398 		zfs_verror(hdl, EZFS_FAULT, fmt, ap);
399 		return (-1);
400 
401 	case EINTR:
402 		zfs_verror(hdl, EZFS_INTR, fmt, ap);
403 		return (-1);
404 
405 	case ECKSUM:
406 		zfs_verror(hdl, EZFS_CKSUM, fmt, ap);
407 		return (-1);
408 	}
409 
410 	return (0);
411 }
412 
413 int
414 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
415 {
416 	return (zfs_standard_error_fmt(hdl, error, "%s", msg));
417 }
418 
419 int
420 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
421 {
422 	va_list ap;
423 
424 	va_start(ap, fmt);
425 
426 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
427 		va_end(ap);
428 		return (-1);
429 	}
430 
431 	switch (error) {
432 	case ENXIO:
433 	case ENODEV:
434 	case EPIPE:
435 		zfs_verror(hdl, EZFS_IO, fmt, ap);
436 		break;
437 
438 	case ENOENT:
439 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
440 		    "dataset does not exist"));
441 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
442 		break;
443 
444 	case ENOSPC:
445 	case EDQUOT:
446 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
447 		break;
448 
449 	case EEXIST:
450 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
451 		    "dataset already exists"));
452 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
453 		break;
454 
455 	case EBUSY:
456 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
457 		    "dataset is busy"));
458 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
459 		break;
460 	case EROFS:
461 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
462 		break;
463 	case ENAMETOOLONG:
464 		zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
465 		break;
466 	case ENOTSUP:
467 		zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
468 		break;
469 	case EAGAIN:
470 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
471 		    "pool I/O is currently suspended"));
472 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
473 		break;
474 	case EREMOTEIO:
475 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
476 		break;
477 	case ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE:
478 	case ZFS_ERR_IOC_CMD_UNAVAIL:
479 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
480 		    "module does not support this operation. A reboot may "
481 		    "be required to enable this operation."));
482 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
483 		break;
484 	case ZFS_ERR_IOC_ARG_UNAVAIL:
485 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
486 		    "module does not support an option for this operation. "
487 		    "A reboot may be required to enable this option."));
488 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
489 		break;
490 	case ZFS_ERR_IOC_ARG_REQUIRED:
491 	case ZFS_ERR_IOC_ARG_BADTYPE:
492 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
493 		break;
494 	case ZFS_ERR_WRONG_PARENT:
495 		zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
496 		break;
497 	case ZFS_ERR_BADPROP:
498 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
499 		break;
500 	case ZFS_ERR_NOT_USER_NAMESPACE:
501 		zfs_verror(hdl, EZFS_NOT_USER_NAMESPACE, fmt, ap);
502 		break;
503 	default:
504 		zfs_error_aux(hdl, "%s", strerror(error));
505 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
506 		break;
507 	}
508 
509 	va_end(ap);
510 	return (-1);
511 }
512 
513 void
514 zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
515     char *errbuf)
516 {
517 	switch (err) {
518 
519 	case ENOSPC:
520 		/*
521 		 * For quotas and reservations, ENOSPC indicates
522 		 * something different; setting a quota or reservation
523 		 * doesn't use any disk space.
524 		 */
525 		switch (prop) {
526 		case ZFS_PROP_QUOTA:
527 		case ZFS_PROP_REFQUOTA:
528 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
529 			    "size is less than current used or "
530 			    "reserved space"));
531 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
532 			break;
533 
534 		case ZFS_PROP_RESERVATION:
535 		case ZFS_PROP_REFRESERVATION:
536 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
537 			    "size is greater than available space"));
538 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
539 			break;
540 
541 		default:
542 			(void) zfs_standard_error(hdl, err, errbuf);
543 			break;
544 		}
545 		break;
546 
547 	case EBUSY:
548 		(void) zfs_standard_error(hdl, EBUSY, errbuf);
549 		break;
550 
551 	case EROFS:
552 		(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
553 		break;
554 
555 	case E2BIG:
556 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
557 		    "property value too long"));
558 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
559 		break;
560 
561 	case ENOTSUP:
562 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
563 		    "pool and or dataset must be upgraded to set this "
564 		    "property or value"));
565 		(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
566 		break;
567 
568 	case ERANGE:
569 		if (prop == ZFS_PROP_COMPRESSION ||
570 		    prop == ZFS_PROP_DNODESIZE ||
571 		    prop == ZFS_PROP_RECORDSIZE) {
572 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
573 			    "property setting is not allowed on "
574 			    "bootable datasets"));
575 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
576 		} else if (prop == ZFS_PROP_CHECKSUM ||
577 		    prop == ZFS_PROP_DEDUP) {
578 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
579 			    "property setting is not allowed on "
580 			    "root pools"));
581 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
582 		} else {
583 			(void) zfs_standard_error(hdl, err, errbuf);
584 		}
585 		break;
586 
587 	case EINVAL:
588 		if (prop == ZPROP_INVAL) {
589 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
590 		} else {
591 			(void) zfs_standard_error(hdl, err, errbuf);
592 		}
593 		break;
594 
595 	case ZFS_ERR_BADPROP:
596 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
597 		break;
598 
599 	case EACCES:
600 		if (prop == ZFS_PROP_KEYLOCATION) {
601 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
602 			    "keylocation may only be set on encryption roots"));
603 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
604 		} else {
605 			(void) zfs_standard_error(hdl, err, errbuf);
606 		}
607 		break;
608 
609 	case EOVERFLOW:
610 		/*
611 		 * This platform can't address a volume this big.
612 		 */
613 #ifdef _ILP32
614 		if (prop == ZFS_PROP_VOLSIZE) {
615 			(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
616 			break;
617 		}
618 		zfs_fallthrough;
619 #endif
620 	default:
621 		(void) zfs_standard_error(hdl, err, errbuf);
622 	}
623 }
624 
625 int
626 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
627 {
628 	return (zpool_standard_error_fmt(hdl, error, "%s", msg));
629 }
630 
631 int
632 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
633 {
634 	va_list ap;
635 
636 	va_start(ap, fmt);
637 
638 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
639 		va_end(ap);
640 		return (-1);
641 	}
642 
643 	switch (error) {
644 	case ENODEV:
645 		zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
646 		break;
647 
648 	case ENOENT:
649 		zfs_error_aux(hdl,
650 		    dgettext(TEXT_DOMAIN, "no such pool or dataset"));
651 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
652 		break;
653 
654 	case EEXIST:
655 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
656 		    "pool already exists"));
657 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
658 		break;
659 
660 	case EBUSY:
661 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
662 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
663 		break;
664 
665 	/* There is no pending operation to cancel */
666 	case ENOTACTIVE:
667 		zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
668 		break;
669 
670 	case ENXIO:
671 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
672 		    "one or more devices is currently unavailable"));
673 		zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
674 		break;
675 
676 	case ENAMETOOLONG:
677 		zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
678 		break;
679 
680 	case ENOTSUP:
681 		zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
682 		break;
683 
684 	case EINVAL:
685 		zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
686 		break;
687 
688 	case ENOSPC:
689 	case EDQUOT:
690 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
691 		break;
692 
693 	case EAGAIN:
694 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
695 		    "pool I/O is currently suspended"));
696 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
697 		break;
698 
699 	case EROFS:
700 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
701 		break;
702 	case EDOM:
703 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
704 		    "block size out of range or does not match"));
705 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
706 		break;
707 	case EREMOTEIO:
708 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
709 		break;
710 	case ZFS_ERR_CHECKPOINT_EXISTS:
711 		zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
712 		break;
713 	case ZFS_ERR_DISCARDING_CHECKPOINT:
714 		zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
715 		break;
716 	case ZFS_ERR_NO_CHECKPOINT:
717 		zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
718 		break;
719 	case ZFS_ERR_DEVRM_IN_PROGRESS:
720 		zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
721 		break;
722 	case ZFS_ERR_VDEV_TOO_BIG:
723 		zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
724 		break;
725 	case ZFS_ERR_EXPORT_IN_PROGRESS:
726 		zfs_verror(hdl, EZFS_EXPORT_IN_PROGRESS, fmt, ap);
727 		break;
728 	case ZFS_ERR_RESILVER_IN_PROGRESS:
729 		zfs_verror(hdl, EZFS_RESILVERING, fmt, ap);
730 		break;
731 	case ZFS_ERR_REBUILD_IN_PROGRESS:
732 		zfs_verror(hdl, EZFS_REBUILDING, fmt, ap);
733 		break;
734 	case ZFS_ERR_BADPROP:
735 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
736 		break;
737 	case ZFS_ERR_VDEV_NOTSUP:
738 		zfs_verror(hdl, EZFS_VDEV_NOTSUP, fmt, ap);
739 		break;
740 	case ZFS_ERR_IOC_CMD_UNAVAIL:
741 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
742 		    "module does not support this operation. A reboot may "
743 		    "be required to enable this operation."));
744 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
745 		break;
746 	case ZFS_ERR_IOC_ARG_UNAVAIL:
747 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
748 		    "module does not support an option for this operation. "
749 		    "A reboot may be required to enable this option."));
750 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
751 		break;
752 	case ZFS_ERR_IOC_ARG_REQUIRED:
753 	case ZFS_ERR_IOC_ARG_BADTYPE:
754 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
755 		break;
756 	default:
757 		zfs_error_aux(hdl, "%s", strerror(error));
758 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
759 	}
760 
761 	va_end(ap);
762 	return (-1);
763 }
764 
765 /*
766  * Display an out of memory error message and abort the current program.
767  */
768 int
769 no_memory(libzfs_handle_t *hdl)
770 {
771 	return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
772 }
773 
774 /*
775  * A safe form of malloc() which will die if the allocation fails.
776  */
777 void *
778 zfs_alloc(libzfs_handle_t *hdl, size_t size)
779 {
780 	void *data;
781 
782 	if ((data = calloc(1, size)) == NULL)
783 		(void) no_memory(hdl);
784 
785 	return (data);
786 }
787 
788 /*
789  * A safe form of asprintf() which will die if the allocation fails.
790  */
791 char *
792 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
793 {
794 	va_list ap;
795 	char *ret;
796 	int err;
797 
798 	va_start(ap, fmt);
799 
800 	err = vasprintf(&ret, fmt, ap);
801 
802 	va_end(ap);
803 
804 	if (err < 0) {
805 		(void) no_memory(hdl);
806 		ret = NULL;
807 	}
808 
809 	return (ret);
810 }
811 
812 /*
813  * A safe form of realloc(), which also zeroes newly allocated space.
814  */
815 void *
816 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
817 {
818 	void *ret;
819 
820 	if ((ret = realloc(ptr, newsize)) == NULL) {
821 		(void) no_memory(hdl);
822 		return (NULL);
823 	}
824 
825 	memset((char *)ret + oldsize, 0, newsize - oldsize);
826 	return (ret);
827 }
828 
829 /*
830  * A safe form of strdup() which will die if the allocation fails.
831  */
832 char *
833 zfs_strdup(libzfs_handle_t *hdl, const char *str)
834 {
835 	char *ret;
836 
837 	if ((ret = strdup(str)) == NULL)
838 		(void) no_memory(hdl);
839 
840 	return (ret);
841 }
842 
843 void
844 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
845 {
846 	hdl->libzfs_printerr = printerr;
847 }
848 
849 /*
850  * Read lines from an open file descriptor and store them in an array of
851  * strings until EOF.  lines[] will be allocated and populated with all the
852  * lines read.  All newlines are replaced with NULL terminators for
853  * convenience.  lines[] must be freed after use with libzfs_free_str_array().
854  *
855  * Returns the number of lines read.
856  */
857 static int
858 libzfs_read_stdout_from_fd(int fd, char **lines[])
859 {
860 
861 	FILE *fp;
862 	int lines_cnt = 0;
863 	size_t len = 0;
864 	char *line = NULL;
865 	char **tmp_lines = NULL, **tmp;
866 
867 	fp = fdopen(fd, "r");
868 	if (fp == NULL) {
869 		close(fd);
870 		return (0);
871 	}
872 	while (getline(&line, &len, fp) != -1) {
873 		tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
874 		if (tmp == NULL) {
875 			/* Return the lines we were able to process */
876 			break;
877 		}
878 		tmp_lines = tmp;
879 
880 		/* Remove newline if not EOF */
881 		if (line[strlen(line) - 1] == '\n')
882 			line[strlen(line) - 1] = '\0';
883 
884 		tmp_lines[lines_cnt] = strdup(line);
885 		if (tmp_lines[lines_cnt] == NULL)
886 			break;
887 		++lines_cnt;
888 	}
889 	free(line);
890 	fclose(fp);
891 	*lines = tmp_lines;
892 	return (lines_cnt);
893 }
894 
895 static int
896 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
897     char **lines[], int *lines_cnt)
898 {
899 	pid_t pid;
900 	int error, devnull_fd;
901 	int link[2];
902 
903 	/*
904 	 * Setup a pipe between our child and parent process if we're
905 	 * reading stdout.
906 	 */
907 	if (lines != NULL && pipe2(link, O_NONBLOCK | O_CLOEXEC) == -1)
908 		return (-EPIPE);
909 
910 	pid = fork();
911 	if (pid == 0) {
912 		/* Child process */
913 		devnull_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
914 
915 		if (devnull_fd < 0)
916 			_exit(-1);
917 
918 		if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
919 			(void) dup2(devnull_fd, STDOUT_FILENO);
920 		else if (lines != NULL) {
921 			/* Save the output to lines[] */
922 			dup2(link[1], STDOUT_FILENO);
923 		}
924 
925 		if (!(flags & STDERR_VERBOSE))
926 			(void) dup2(devnull_fd, STDERR_FILENO);
927 
928 		if (flags & NO_DEFAULT_PATH) {
929 			if (env == NULL)
930 				execv(path, argv);
931 			else
932 				execve(path, argv, env);
933 		} else {
934 			if (env == NULL)
935 				execvp(path, argv);
936 			else
937 				execvpe(path, argv, env);
938 		}
939 
940 		_exit(-1);
941 	} else if (pid > 0) {
942 		/* Parent process */
943 		int status;
944 
945 		while ((error = waitpid(pid, &status, 0)) == -1 &&
946 		    errno == EINTR)
947 			;
948 		if (error < 0 || !WIFEXITED(status))
949 			return (-1);
950 
951 		if (lines != NULL) {
952 			close(link[1]);
953 			*lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
954 		}
955 		return (WEXITSTATUS(status));
956 	}
957 
958 	return (-1);
959 }
960 
961 int
962 libzfs_run_process(const char *path, char *argv[], int flags)
963 {
964 	return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
965 }
966 
967 /*
968  * Run a command and store its stdout lines in an array of strings (lines[]).
969  * lines[] is allocated and populated for you, and the number of lines is set in
970  * lines_cnt.  lines[] must be freed after use with libzfs_free_str_array().
971  * All newlines (\n) in lines[] are terminated for convenience.
972  */
973 int
974 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
975     char **lines[], int *lines_cnt)
976 {
977 	return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
978 }
979 
980 /*
981  * Same as libzfs_run_process_get_stdout(), but run without $PATH set.  This
982  * means that *path needs to be the full path to the executable.
983  */
984 int
985 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
986     char *env[], char **lines[], int *lines_cnt)
987 {
988 	return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
989 	    lines, lines_cnt));
990 }
991 
992 /*
993  * Free an array of strings.  Free both the strings contained in the array and
994  * the array itself.
995  */
996 void
997 libzfs_free_str_array(char **strs, int count)
998 {
999 	while (--count >= 0)
1000 		free(strs[count]);
1001 
1002 	free(strs);
1003 }
1004 
1005 /*
1006  * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
1007  * a non-zero number.
1008  *
1009  * Returns 0 otherwise.
1010  */
1011 boolean_t
1012 libzfs_envvar_is_set(const char *envvar)
1013 {
1014 	char *env = getenv(envvar);
1015 	return (env && (strtoul(env, NULL, 0) > 0 ||
1016 	    (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
1017 	    (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)));
1018 }
1019 
1020 libzfs_handle_t *
1021 libzfs_init(void)
1022 {
1023 	libzfs_handle_t *hdl;
1024 	int error;
1025 	char *env;
1026 
1027 	if ((error = libzfs_load_module()) != 0) {
1028 		errno = error;
1029 		return (NULL);
1030 	}
1031 
1032 	if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1033 		return (NULL);
1034 	}
1035 
1036 	if (regcomp(&hdl->libzfs_urire, URI_REGEX, 0) != 0) {
1037 		free(hdl);
1038 		return (NULL);
1039 	}
1040 
1041 	if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL|O_CLOEXEC)) < 0) {
1042 		free(hdl);
1043 		return (NULL);
1044 	}
1045 
1046 	if (libzfs_core_init() != 0) {
1047 		(void) close(hdl->libzfs_fd);
1048 		free(hdl);
1049 		return (NULL);
1050 	}
1051 
1052 	zfs_prop_init();
1053 	zpool_prop_init();
1054 	zpool_feature_init();
1055 	vdev_prop_init();
1056 	libzfs_mnttab_init(hdl);
1057 	fletcher_4_init();
1058 
1059 	if (getenv("ZFS_PROP_DEBUG") != NULL) {
1060 		hdl->libzfs_prop_debug = B_TRUE;
1061 	}
1062 	if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1063 		if ((error = zfs_nicestrtonum(hdl, env,
1064 		    &hdl->libzfs_max_nvlist))) {
1065 			errno = error;
1066 			(void) close(hdl->libzfs_fd);
1067 			free(hdl);
1068 			return (NULL);
1069 		}
1070 	} else {
1071 		hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1072 	}
1073 
1074 	/*
1075 	 * For testing, remove some settable properties and features
1076 	 */
1077 	if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1078 		zprop_desc_t *proptbl;
1079 
1080 		proptbl = zpool_prop_get_table();
1081 		proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1082 
1083 		proptbl = zfs_prop_get_table();
1084 		proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1085 
1086 		zfeature_info_t *ftbl = spa_feature_table;
1087 		ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1088 	}
1089 
1090 	return (hdl);
1091 }
1092 
1093 void
1094 libzfs_fini(libzfs_handle_t *hdl)
1095 {
1096 	(void) close(hdl->libzfs_fd);
1097 	zpool_free_handles(hdl);
1098 	namespace_clear(hdl);
1099 	libzfs_mnttab_fini(hdl);
1100 	libzfs_core_fini();
1101 	regfree(&hdl->libzfs_urire);
1102 	fletcher_4_fini();
1103 #if LIBFETCH_DYNAMIC
1104 	if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1105 		(void) dlclose(hdl->libfetch);
1106 	free(hdl->libfetch_load_error);
1107 #endif
1108 	free(hdl);
1109 }
1110 
1111 libzfs_handle_t *
1112 zpool_get_handle(zpool_handle_t *zhp)
1113 {
1114 	return (zhp->zpool_hdl);
1115 }
1116 
1117 libzfs_handle_t *
1118 zfs_get_handle(zfs_handle_t *zhp)
1119 {
1120 	return (zhp->zfs_hdl);
1121 }
1122 
1123 zpool_handle_t *
1124 zfs_get_pool_handle(const zfs_handle_t *zhp)
1125 {
1126 	return (zhp->zpool_hdl);
1127 }
1128 
1129 /*
1130  * Given a name, determine whether or not it's a valid path
1131  * (starts with '/' or "./").  If so, walk the mnttab trying
1132  * to match the device number.  If not, treat the path as an
1133  * fs/vol/snap/bkmark name.
1134  */
1135 zfs_handle_t *
1136 zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
1137 {
1138 	struct stat64 statbuf;
1139 	struct extmnttab entry;
1140 
1141 	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1142 		/*
1143 		 * It's not a valid path, assume it's a name of type 'argtype'.
1144 		 */
1145 		return (zfs_open(hdl, path, argtype));
1146 	}
1147 
1148 	if (getextmntent(path, &entry, &statbuf) != 0)
1149 		return (NULL);
1150 
1151 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1152 		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1153 		    path);
1154 		return (NULL);
1155 	}
1156 
1157 	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1158 }
1159 
1160 /*
1161  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1162  * an ioctl().
1163  */
1164 void
1165 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1166 {
1167 	if (len == 0)
1168 		len = 256 * 1024;
1169 	zc->zc_nvlist_dst_size = len;
1170 	zc->zc_nvlist_dst =
1171 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1172 }
1173 
1174 /*
1175  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
1176  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1177  * filled in by the kernel to indicate the actual required size.
1178  */
1179 void
1180 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1181 {
1182 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1183 	zc->zc_nvlist_dst =
1184 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1185 }
1186 
1187 /*
1188  * Called to free the src and dst nvlists stored in the command structure.
1189  */
1190 void
1191 zcmd_free_nvlists(zfs_cmd_t *zc)
1192 {
1193 	free((void *)(uintptr_t)zc->zc_nvlist_conf);
1194 	free((void *)(uintptr_t)zc->zc_nvlist_src);
1195 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1196 	zc->zc_nvlist_conf = 0;
1197 	zc->zc_nvlist_src = 0;
1198 	zc->zc_nvlist_dst = 0;
1199 }
1200 
1201 static void
1202 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1203     nvlist_t *nvl)
1204 {
1205 	char *packed;
1206 
1207 	size_t len = fnvlist_size(nvl);
1208 	packed = zfs_alloc(hdl, len);
1209 
1210 	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1211 
1212 	*outnv = (uint64_t)(uintptr_t)packed;
1213 	*outlen = len;
1214 }
1215 
1216 void
1217 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1218 {
1219 	zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1220 	    &zc->zc_nvlist_conf_size, nvl);
1221 }
1222 
1223 void
1224 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1225 {
1226 	zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1227 	    &zc->zc_nvlist_src_size, nvl);
1228 }
1229 
1230 /*
1231  * Unpacks an nvlist from the ZFS ioctl command structure.
1232  */
1233 int
1234 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1235 {
1236 	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1237 	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1238 		return (no_memory(hdl));
1239 
1240 	return (0);
1241 }
1242 
1243 /*
1244  * ================================================================
1245  * API shared by zfs and zpool property management
1246  * ================================================================
1247  */
1248 
1249 static void
1250 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1251 {
1252 	zprop_list_t *pl;
1253 	int i;
1254 	char *title;
1255 	size_t len;
1256 
1257 	cbp->cb_first = B_FALSE;
1258 	if (cbp->cb_scripted)
1259 		return;
1260 
1261 	/*
1262 	 * Start with the length of the column headers.
1263 	 */
1264 	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1265 	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1266 	    "PROPERTY"));
1267 	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1268 	    "VALUE"));
1269 	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1270 	    "RECEIVED"));
1271 	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1272 	    "SOURCE"));
1273 
1274 	/* first property is always NAME */
1275 	assert(cbp->cb_proplist->pl_prop ==
1276 	    ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1277 	    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME)));
1278 
1279 	/*
1280 	 * Go through and calculate the widths for each column.  For the
1281 	 * 'source' column, we kludge it up by taking the worst-case scenario of
1282 	 * inheriting from the longest name.  This is acceptable because in the
1283 	 * majority of cases 'SOURCE' is the last column displayed, and we don't
1284 	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
1285 	 * if the name of the property is much longer than any values we find.
1286 	 */
1287 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1288 		/*
1289 		 * 'PROPERTY' column
1290 		 */
1291 		if (pl->pl_prop != ZPROP_USERPROP) {
1292 			const char *propname = (type == ZFS_TYPE_POOL) ?
1293 			    zpool_prop_to_name(pl->pl_prop) :
1294 			    ((type == ZFS_TYPE_VDEV) ?
1295 			    vdev_prop_to_name(pl->pl_prop) :
1296 			    zfs_prop_to_name(pl->pl_prop));
1297 
1298 			assert(propname != NULL);
1299 			len = strlen(propname);
1300 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1301 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1302 		} else {
1303 			assert(pl->pl_user_prop != NULL);
1304 			len = strlen(pl->pl_user_prop);
1305 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1306 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1307 		}
1308 
1309 		/*
1310 		 * 'VALUE' column.  The first property is always the 'name'
1311 		 * property that was tacked on either by /sbin/zfs's
1312 		 * zfs_do_get() or when calling zprop_expand_list(), so we
1313 		 * ignore its width.  If the user specified the name property
1314 		 * to display, then it will be later in the list in any case.
1315 		 */
1316 		if (pl != cbp->cb_proplist &&
1317 		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1318 			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1319 
1320 		/* 'RECEIVED' column. */
1321 		if (pl != cbp->cb_proplist &&
1322 		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1323 			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1324 
1325 		/*
1326 		 * 'NAME' and 'SOURCE' columns
1327 		 */
1328 		if (pl->pl_prop == ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1329 		    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME :
1330 		    ZFS_PROP_NAME)) && pl->pl_width >
1331 		    cbp->cb_colwidths[GET_COL_NAME]) {
1332 			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1333 			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1334 			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1335 		}
1336 	}
1337 
1338 	/*
1339 	 * Now go through and print the headers.
1340 	 */
1341 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1342 		switch (cbp->cb_columns[i]) {
1343 		case GET_COL_NAME:
1344 			title = dgettext(TEXT_DOMAIN, "NAME");
1345 			break;
1346 		case GET_COL_PROPERTY:
1347 			title = dgettext(TEXT_DOMAIN, "PROPERTY");
1348 			break;
1349 		case GET_COL_VALUE:
1350 			title = dgettext(TEXT_DOMAIN, "VALUE");
1351 			break;
1352 		case GET_COL_RECVD:
1353 			title = dgettext(TEXT_DOMAIN, "RECEIVED");
1354 			break;
1355 		case GET_COL_SOURCE:
1356 			title = dgettext(TEXT_DOMAIN, "SOURCE");
1357 			break;
1358 		default:
1359 			title = NULL;
1360 		}
1361 
1362 		if (title != NULL) {
1363 			if (i == (ZFS_GET_NCOLS - 1) ||
1364 			    cbp->cb_columns[i + 1] == GET_COL_NONE)
1365 				(void) printf("%s", title);
1366 			else
1367 				(void) printf("%-*s  ",
1368 				    cbp->cb_colwidths[cbp->cb_columns[i]],
1369 				    title);
1370 		}
1371 	}
1372 	(void) printf("\n");
1373 }
1374 
1375 /*
1376  * Display a single line of output, according to the settings in the callback
1377  * structure.
1378  */
1379 void
1380 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1381     const char *propname, const char *value, zprop_source_t sourcetype,
1382     const char *source, const char *recvd_value)
1383 {
1384 	int i;
1385 	const char *str = NULL;
1386 	char buf[128];
1387 
1388 	/*
1389 	 * Ignore those source types that the user has chosen to ignore.
1390 	 */
1391 	if ((sourcetype & cbp->cb_sources) == 0)
1392 		return;
1393 
1394 	if (cbp->cb_first)
1395 		zprop_print_headers(cbp, cbp->cb_type);
1396 
1397 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1398 		switch (cbp->cb_columns[i]) {
1399 		case GET_COL_NAME:
1400 			str = name;
1401 			break;
1402 
1403 		case GET_COL_PROPERTY:
1404 			str = propname;
1405 			break;
1406 
1407 		case GET_COL_VALUE:
1408 			str = value;
1409 			break;
1410 
1411 		case GET_COL_SOURCE:
1412 			switch (sourcetype) {
1413 			case ZPROP_SRC_NONE:
1414 				str = "-";
1415 				break;
1416 
1417 			case ZPROP_SRC_DEFAULT:
1418 				str = "default";
1419 				break;
1420 
1421 			case ZPROP_SRC_LOCAL:
1422 				str = "local";
1423 				break;
1424 
1425 			case ZPROP_SRC_TEMPORARY:
1426 				str = "temporary";
1427 				break;
1428 
1429 			case ZPROP_SRC_INHERITED:
1430 				(void) snprintf(buf, sizeof (buf),
1431 				    "inherited from %s", source);
1432 				str = buf;
1433 				break;
1434 			case ZPROP_SRC_RECEIVED:
1435 				str = "received";
1436 				break;
1437 
1438 			default:
1439 				str = NULL;
1440 				assert(!"unhandled zprop_source_t");
1441 			}
1442 			break;
1443 
1444 		case GET_COL_RECVD:
1445 			str = (recvd_value == NULL ? "-" : recvd_value);
1446 			break;
1447 
1448 		default:
1449 			continue;
1450 		}
1451 
1452 		if (i == (ZFS_GET_NCOLS - 1) ||
1453 		    cbp->cb_columns[i + 1] == GET_COL_NONE)
1454 			(void) printf("%s", str);
1455 		else if (cbp->cb_scripted)
1456 			(void) printf("%s\t", str);
1457 		else
1458 			(void) printf("%-*s  ",
1459 			    cbp->cb_colwidths[cbp->cb_columns[i]],
1460 			    str);
1461 	}
1462 
1463 	(void) printf("\n");
1464 }
1465 
1466 /*
1467  * Given a numeric suffix, convert the value into a number of bits that the
1468  * resulting value must be shifted.
1469  */
1470 static int
1471 str2shift(libzfs_handle_t *hdl, const char *buf)
1472 {
1473 	const char *ends = "BKMGTPEZ";
1474 	int i;
1475 
1476 	if (buf[0] == '\0')
1477 		return (0);
1478 	for (i = 0; i < strlen(ends); i++) {
1479 		if (toupper(buf[0]) == ends[i])
1480 			break;
1481 	}
1482 	if (i == strlen(ends)) {
1483 		if (hdl)
1484 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1485 			    "invalid numeric suffix '%s'"), buf);
1486 		return (-1);
1487 	}
1488 
1489 	/*
1490 	 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1491 	 * However, 'BB' and 'BiB' are disallowed.
1492 	 */
1493 	if (buf[1] == '\0' ||
1494 	    (toupper(buf[0]) != 'B' &&
1495 	    ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1496 	    (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1497 	    buf[3] == '\0'))))
1498 		return (10 * i);
1499 
1500 	if (hdl)
1501 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1502 		    "invalid numeric suffix '%s'"), buf);
1503 	return (-1);
1504 }
1505 
1506 /*
1507  * Convert a string of the form '100G' into a real number.  Used when setting
1508  * properties or creating a volume.  'buf' is used to place an extended error
1509  * message for the caller to use.
1510  */
1511 int
1512 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1513 {
1514 	char *end;
1515 	int shift;
1516 
1517 	*num = 0;
1518 
1519 	/* Check to see if this looks like a number.  */
1520 	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1521 		if (hdl)
1522 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1523 			    "bad numeric value '%s'"), value);
1524 		return (-1);
1525 	}
1526 
1527 	/* Rely on strtoull() to process the numeric portion.  */
1528 	errno = 0;
1529 	*num = strtoull(value, &end, 10);
1530 
1531 	/*
1532 	 * Check for ERANGE, which indicates that the value is too large to fit
1533 	 * in a 64-bit value.
1534 	 */
1535 	if (errno == ERANGE) {
1536 		if (hdl)
1537 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1538 			    "numeric value is too large"));
1539 		return (-1);
1540 	}
1541 
1542 	/*
1543 	 * If we have a decimal value, then do the computation with floating
1544 	 * point arithmetic.  Otherwise, use standard arithmetic.
1545 	 */
1546 	if (*end == '.') {
1547 		double fval = strtod(value, &end);
1548 
1549 		if ((shift = str2shift(hdl, end)) == -1)
1550 			return (-1);
1551 
1552 		fval *= pow(2, shift);
1553 
1554 		/*
1555 		 * UINT64_MAX is not exactly representable as a double.
1556 		 * The closest representation is UINT64_MAX + 1, so we
1557 		 * use a >= comparison instead of > for the bounds check.
1558 		 */
1559 		if (fval >= (double)UINT64_MAX) {
1560 			if (hdl)
1561 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1562 				    "numeric value is too large"));
1563 			return (-1);
1564 		}
1565 
1566 		*num = (uint64_t)fval;
1567 	} else {
1568 		if ((shift = str2shift(hdl, end)) == -1)
1569 			return (-1);
1570 
1571 		/* Check for overflow */
1572 		if (shift >= 64 || (*num << shift) >> shift != *num) {
1573 			if (hdl)
1574 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1575 				    "numeric value is too large"));
1576 			return (-1);
1577 		}
1578 
1579 		*num <<= shift;
1580 	}
1581 
1582 	return (0);
1583 }
1584 
1585 /*
1586  * Given a propname=value nvpair to set, parse any numeric properties
1587  * (index, boolean, etc) if they are specified as strings and add the
1588  * resulting nvpair to the returned nvlist.
1589  *
1590  * At the DSL layer, all properties are either 64-bit numbers or strings.
1591  * We want the user to be able to ignore this fact and specify properties
1592  * as native values (numbers, for example) or as strings (to simplify
1593  * command line utilities).  This also handles converting index types
1594  * (compression, checksum, etc) from strings to their on-disk index.
1595  */
1596 int
1597 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1598     zfs_type_t type, nvlist_t *ret, const char **svalp, uint64_t *ivalp,
1599     const char *errbuf)
1600 {
1601 	data_type_t datatype = nvpair_type(elem);
1602 	zprop_type_t proptype;
1603 	const char *propname;
1604 	const char *value;
1605 	boolean_t isnone = B_FALSE;
1606 	boolean_t isauto = B_FALSE;
1607 	int err = 0;
1608 
1609 	if (type == ZFS_TYPE_POOL) {
1610 		proptype = zpool_prop_get_type(prop);
1611 		propname = zpool_prop_to_name(prop);
1612 	} else if (type == ZFS_TYPE_VDEV) {
1613 		proptype = vdev_prop_get_type(prop);
1614 		propname = vdev_prop_to_name(prop);
1615 	} else {
1616 		proptype = zfs_prop_get_type(prop);
1617 		propname = zfs_prop_to_name(prop);
1618 	}
1619 
1620 	/*
1621 	 * Convert any properties to the internal DSL value types.
1622 	 */
1623 	*svalp = NULL;
1624 	*ivalp = 0;
1625 
1626 	switch (proptype) {
1627 	case PROP_TYPE_STRING:
1628 		if (datatype != DATA_TYPE_STRING) {
1629 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1630 			    "'%s' must be a string"), nvpair_name(elem));
1631 			goto error;
1632 		}
1633 		err = nvpair_value_string(elem, svalp);
1634 		if (err != 0) {
1635 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1636 			    "'%s' is invalid"), nvpair_name(elem));
1637 			goto error;
1638 		}
1639 		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1640 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1641 			    "'%s' is too long"), nvpair_name(elem));
1642 			goto error;
1643 		}
1644 		break;
1645 
1646 	case PROP_TYPE_NUMBER:
1647 		if (datatype == DATA_TYPE_STRING) {
1648 			(void) nvpair_value_string(elem, &value);
1649 			if (strcmp(value, "none") == 0) {
1650 				isnone = B_TRUE;
1651 			} else if (strcmp(value, "auto") == 0) {
1652 				isauto = B_TRUE;
1653 			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1654 				goto error;
1655 			}
1656 		} else if (datatype == DATA_TYPE_UINT64) {
1657 			(void) nvpair_value_uint64(elem, ivalp);
1658 		} else {
1659 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1660 			    "'%s' must be a number"), nvpair_name(elem));
1661 			goto error;
1662 		}
1663 
1664 		/*
1665 		 * Quota special: force 'none' and don't allow 0.
1666 		 */
1667 		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1668 		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1669 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1670 			    "use 'none' to disable quota/refquota"));
1671 			goto error;
1672 		}
1673 
1674 		/*
1675 		 * Special handling for "*_limit=none". In this case it's not
1676 		 * 0 but UINT64_MAX.
1677 		 */
1678 		if ((type & ZFS_TYPE_DATASET) && isnone &&
1679 		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1680 		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1681 			*ivalp = UINT64_MAX;
1682 		}
1683 
1684 		/*
1685 		 * Special handling for "checksum_*=none". In this case it's not
1686 		 * 0 but UINT64_MAX.
1687 		 */
1688 		if ((type & ZFS_TYPE_VDEV) && isnone &&
1689 		    (prop == VDEV_PROP_CHECKSUM_N ||
1690 		    prop == VDEV_PROP_CHECKSUM_T ||
1691 		    prop == VDEV_PROP_IO_N ||
1692 		    prop == VDEV_PROP_IO_T)) {
1693 			*ivalp = UINT64_MAX;
1694 		}
1695 
1696 		/*
1697 		 * Special handling for setting 'refreservation' to 'auto'.  Use
1698 		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1699 		 * 'auto' is only allowed on volumes.
1700 		 */
1701 		if (isauto) {
1702 			switch (prop) {
1703 			case ZFS_PROP_REFRESERVATION:
1704 				if ((type & ZFS_TYPE_VOLUME) == 0) {
1705 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1706 					    "'%s=auto' only allowed on "
1707 					    "volumes"), nvpair_name(elem));
1708 					goto error;
1709 				}
1710 				*ivalp = UINT64_MAX;
1711 				break;
1712 			default:
1713 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1714 				    "'auto' is invalid value for '%s'"),
1715 				    nvpair_name(elem));
1716 				goto error;
1717 			}
1718 		}
1719 
1720 		break;
1721 
1722 	case PROP_TYPE_INDEX:
1723 		if (datatype != DATA_TYPE_STRING) {
1724 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1725 			    "'%s' must be a string"), nvpair_name(elem));
1726 			goto error;
1727 		}
1728 
1729 		(void) nvpair_value_string(elem, &value);
1730 
1731 		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1732 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1733 			    "'%s' must be one of '%s'"), propname,
1734 			    zprop_values(prop, type));
1735 			goto error;
1736 		}
1737 		break;
1738 
1739 	default:
1740 		abort();
1741 	}
1742 
1743 	/*
1744 	 * Add the result to our return set of properties.
1745 	 */
1746 	if (*svalp != NULL) {
1747 		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1748 			(void) no_memory(hdl);
1749 			return (-1);
1750 		}
1751 	} else {
1752 		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1753 			(void) no_memory(hdl);
1754 			return (-1);
1755 		}
1756 	}
1757 
1758 	return (0);
1759 error:
1760 	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1761 	return (-1);
1762 }
1763 
1764 static int
1765 addlist(libzfs_handle_t *hdl, const char *propname, zprop_list_t **listp,
1766     zfs_type_t type)
1767 {
1768 	int prop = zprop_name_to_prop(propname, type);
1769 	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1770 		prop = ZPROP_INVAL;
1771 
1772 	/*
1773 	 * Return failure if no property table entry was found and this isn't
1774 	 * a user-defined property.
1775 	 */
1776 	if (prop == ZPROP_USERPROP && ((type == ZFS_TYPE_POOL &&
1777 	    !zpool_prop_feature(propname) &&
1778 	    !zpool_prop_unsupported(propname)) ||
1779 	    ((type == ZFS_TYPE_DATASET) && !zfs_prop_user(propname) &&
1780 	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)) ||
1781 	    ((type == ZFS_TYPE_VDEV) && !vdev_prop_user(propname)))) {
1782 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1783 		    "invalid property '%s'"), propname);
1784 		return (zfs_error(hdl, EZFS_BADPROP,
1785 		    dgettext(TEXT_DOMAIN, "bad property list")));
1786 	}
1787 
1788 	zprop_list_t *entry = zfs_alloc(hdl, sizeof (*entry));
1789 
1790 	entry->pl_prop = prop;
1791 	if (prop == ZPROP_USERPROP) {
1792 		entry->pl_user_prop = zfs_strdup(hdl, propname);
1793 		entry->pl_width = strlen(propname);
1794 	} else {
1795 		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1796 		    type);
1797 	}
1798 
1799 	*listp = entry;
1800 
1801 	return (0);
1802 }
1803 
1804 /*
1805  * Given a comma-separated list of properties, construct a property list
1806  * containing both user-defined and native properties.  This function will
1807  * return a NULL list if 'all' is specified, which can later be expanded
1808  * by zprop_expand_list().
1809  */
1810 int
1811 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1812     zfs_type_t type)
1813 {
1814 	*listp = NULL;
1815 
1816 	/*
1817 	 * If 'all' is specified, return a NULL list.
1818 	 */
1819 	if (strcmp(props, "all") == 0)
1820 		return (0);
1821 
1822 	/*
1823 	 * If no props were specified, return an error.
1824 	 */
1825 	if (props[0] == '\0') {
1826 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1827 		    "no properties specified"));
1828 		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1829 		    "bad property list")));
1830 	}
1831 
1832 	for (char *p; (p = strsep(&props, ",")); )
1833 		if (strcmp(p, "space") == 0) {
1834 			static const char *const spaceprops[] = {
1835 				"name", "avail", "used", "usedbysnapshots",
1836 				"usedbydataset", "usedbyrefreservation",
1837 				"usedbychildren"
1838 			};
1839 
1840 			for (int i = 0; i < ARRAY_SIZE(spaceprops); i++) {
1841 				if (addlist(hdl, spaceprops[i], listp, type))
1842 					return (-1);
1843 				listp = &(*listp)->pl_next;
1844 			}
1845 		} else {
1846 			if (addlist(hdl, p, listp, type))
1847 				return (-1);
1848 			listp = &(*listp)->pl_next;
1849 		}
1850 
1851 	return (0);
1852 }
1853 
1854 void
1855 zprop_free_list(zprop_list_t *pl)
1856 {
1857 	zprop_list_t *next;
1858 
1859 	while (pl != NULL) {
1860 		next = pl->pl_next;
1861 		free(pl->pl_user_prop);
1862 		free(pl);
1863 		pl = next;
1864 	}
1865 }
1866 
1867 typedef struct expand_data {
1868 	zprop_list_t	**last;
1869 	libzfs_handle_t	*hdl;
1870 	zfs_type_t type;
1871 } expand_data_t;
1872 
1873 static int
1874 zprop_expand_list_cb(int prop, void *cb)
1875 {
1876 	zprop_list_t *entry;
1877 	expand_data_t *edp = cb;
1878 
1879 	entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t));
1880 
1881 	entry->pl_prop = prop;
1882 	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1883 	entry->pl_all = B_TRUE;
1884 
1885 	*(edp->last) = entry;
1886 	edp->last = &entry->pl_next;
1887 
1888 	return (ZPROP_CONT);
1889 }
1890 
1891 int
1892 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1893 {
1894 	zprop_list_t *entry;
1895 	zprop_list_t **last;
1896 	expand_data_t exp;
1897 
1898 	if (*plp == NULL) {
1899 		/*
1900 		 * If this is the very first time we've been called for an 'all'
1901 		 * specification, expand the list to include all native
1902 		 * properties.
1903 		 */
1904 		last = plp;
1905 
1906 		exp.last = last;
1907 		exp.hdl = hdl;
1908 		exp.type = type;
1909 
1910 		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1911 		    B_FALSE, type) == ZPROP_INVAL)
1912 			return (-1);
1913 
1914 		/*
1915 		 * Add 'name' to the beginning of the list, which is handled
1916 		 * specially.
1917 		 */
1918 		entry = zfs_alloc(hdl, sizeof (zprop_list_t));
1919 		entry->pl_prop = ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1920 		    ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME));
1921 		entry->pl_width = zprop_width(entry->pl_prop,
1922 		    &entry->pl_fixed, type);
1923 		entry->pl_all = B_TRUE;
1924 		entry->pl_next = *plp;
1925 		*plp = entry;
1926 	}
1927 	return (0);
1928 }
1929 
1930 int
1931 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1932     zfs_type_t type)
1933 {
1934 	return (zprop_iter_common(func, cb, show_all, ordered, type));
1935 }
1936 
1937 const char *
1938 zfs_version_userland(void)
1939 {
1940 	return (ZFS_META_ALIAS);
1941 }
1942 
1943 /*
1944  * Prints both zfs userland and kernel versions
1945  * Returns 0 on success, and -1 on error
1946  */
1947 int
1948 zfs_version_print(void)
1949 {
1950 	(void) puts(ZFS_META_ALIAS);
1951 
1952 	char *kver = zfs_version_kernel();
1953 	if (kver == NULL) {
1954 		fprintf(stderr, "zfs_version_kernel() failed: %s\n",
1955 		    strerror(errno));
1956 		return (-1);
1957 	}
1958 
1959 	(void) printf("zfs-kmod-%s\n", kver);
1960 	free(kver);
1961 	return (0);
1962 }
1963 
1964 /*
1965  * Return 1 if the user requested ANSI color output, and our terminal supports
1966  * it.  Return 0 for no color.
1967  */
1968 static int
1969 use_color(void)
1970 {
1971 	static int use_color = -1;
1972 	char *term;
1973 
1974 	/*
1975 	 * Optimization:
1976 	 *
1977 	 * For each zpool invocation, we do a single check to see if we should
1978 	 * be using color or not, and cache that value for the lifetime of the
1979 	 * the zpool command.  That makes it cheap to call use_color() when
1980 	 * we're printing with color.  We assume that the settings are not going
1981 	 * to change during the invocation of a zpool command (the user isn't
1982 	 * going to change the ZFS_COLOR value while zpool is running, for
1983 	 * example).
1984 	 */
1985 	if (use_color != -1) {
1986 		/*
1987 		 * We've already figured out if we should be using color or
1988 		 * not.  Return the cached value.
1989 		 */
1990 		return (use_color);
1991 	}
1992 
1993 	term = getenv("TERM");
1994 	/*
1995 	 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
1996 	 * output.  However if NO_COLOR is set (https://no-color.org/) then
1997 	 * don't use it.  Also, don't use color if terminal doesn't support
1998 	 * it.
1999 	 */
2000 	if (libzfs_envvar_is_set("ZFS_COLOR") &&
2001 	    !libzfs_envvar_is_set("NO_COLOR") &&
2002 	    isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
2003 	    strcmp("unknown", term) != 0) {
2004 		/* Color supported */
2005 		use_color = 1;
2006 	} else {
2007 		use_color = 0;
2008 	}
2009 
2010 	return (use_color);
2011 }
2012 
2013 /*
2014  * The functions color_start() and color_end() are used for when you want
2015  * to colorize a block of text.
2016  *
2017  * For example:
2018  * color_start(ANSI_RED)
2019  * printf("hello");
2020  * printf("world");
2021  * color_end();
2022  */
2023 void
2024 color_start(const char *color)
2025 {
2026 	if (color && use_color()) {
2027 		fputs(color, stdout);
2028 		fflush(stdout);
2029 	}
2030 }
2031 
2032 void
2033 color_end(void)
2034 {
2035 	if (use_color()) {
2036 		fputs(ANSI_RESET, stdout);
2037 		fflush(stdout);
2038 	}
2039 
2040 }
2041 
2042 /*
2043  * printf() with a color. If color is NULL, then do a normal printf.
2044  */
2045 int
2046 printf_color(const char *color, const char *format, ...)
2047 {
2048 	va_list aptr;
2049 	int rc;
2050 
2051 	if (color)
2052 		color_start(color);
2053 
2054 	va_start(aptr, format);
2055 	rc = vprintf(format, aptr);
2056 	va_end(aptr);
2057 
2058 	if (color)
2059 		color_end();
2060 
2061 	return (rc);
2062 }
2063