xref: /freebsd-13-stable/sys/contrib/openzfs/lib/libzfs/libzfs_util.c (revision b9c2c366db1beb2ed276947056f45938ad8f57ec)
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 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
libzfs_errno(libzfs_handle_t * hdl)73 libzfs_errno(libzfs_handle_t *hdl)
74 {
75 	return (hdl->libzfs_error);
76 }
77 
78 const char *
libzfs_error_action(libzfs_handle_t * hdl)79 libzfs_error_action(libzfs_handle_t *hdl)
80 {
81 	return (hdl->libzfs_action);
82 }
83 
84 const char *
libzfs_error_description(libzfs_handle_t * hdl)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_UNKNOWN:
302 		return (dgettext(TEXT_DOMAIN, "unknown error"));
303 	default:
304 		assert(hdl->libzfs_error == 0);
305 		return (dgettext(TEXT_DOMAIN, "no error"));
306 	}
307 }
308 
309 /*PRINTFLIKE2*/
310 void
zfs_error_aux(libzfs_handle_t * hdl,const char * fmt,...)311 zfs_error_aux(libzfs_handle_t *hdl, const char *fmt, ...)
312 {
313 	va_list ap;
314 
315 	va_start(ap, fmt);
316 
317 	(void) vsnprintf(hdl->libzfs_desc, sizeof (hdl->libzfs_desc),
318 	    fmt, ap);
319 	hdl->libzfs_desc_active = 1;
320 
321 	va_end(ap);
322 }
323 
324 static void
zfs_verror(libzfs_handle_t * hdl,int error,const char * fmt,va_list ap)325 zfs_verror(libzfs_handle_t *hdl, int error, const char *fmt, va_list ap)
326 {
327 	(void) vsnprintf(hdl->libzfs_action, sizeof (hdl->libzfs_action),
328 	    fmt, ap);
329 	hdl->libzfs_error = error;
330 
331 	if (hdl->libzfs_desc_active)
332 		hdl->libzfs_desc_active = 0;
333 	else
334 		hdl->libzfs_desc[0] = '\0';
335 
336 	if (hdl->libzfs_printerr) {
337 		if (error == EZFS_UNKNOWN) {
338 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "internal "
339 			    "error: %s: %s\n"), hdl->libzfs_action,
340 			    libzfs_error_description(hdl));
341 			abort();
342 		}
343 
344 		(void) fprintf(stderr, "%s: %s\n", hdl->libzfs_action,
345 		    libzfs_error_description(hdl));
346 		if (error == EZFS_NOMEM)
347 			exit(1);
348 	}
349 }
350 
351 int
zfs_error(libzfs_handle_t * hdl,int error,const char * msg)352 zfs_error(libzfs_handle_t *hdl, int error, const char *msg)
353 {
354 	return (zfs_error_fmt(hdl, error, "%s", msg));
355 }
356 
357 /*PRINTFLIKE3*/
358 int
zfs_error_fmt(libzfs_handle_t * hdl,int error,const char * fmt,...)359 zfs_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
360 {
361 	va_list ap;
362 
363 	va_start(ap, fmt);
364 
365 	zfs_verror(hdl, error, fmt, ap);
366 
367 	va_end(ap);
368 
369 	return (-1);
370 }
371 
372 static int
zfs_common_error(libzfs_handle_t * hdl,int error,const char * fmt,va_list ap)373 zfs_common_error(libzfs_handle_t *hdl, int error, const char *fmt,
374     va_list ap)
375 {
376 	switch (error) {
377 	case EPERM:
378 	case EACCES:
379 		zfs_verror(hdl, EZFS_PERM, fmt, ap);
380 		return (-1);
381 
382 	case ECANCELED:
383 		zfs_verror(hdl, EZFS_NODELEGATION, fmt, ap);
384 		return (-1);
385 
386 	case EIO:
387 		zfs_verror(hdl, EZFS_IO, fmt, ap);
388 		return (-1);
389 
390 	case EFAULT:
391 		zfs_verror(hdl, EZFS_FAULT, fmt, ap);
392 		return (-1);
393 
394 	case EINTR:
395 		zfs_verror(hdl, EZFS_INTR, fmt, ap);
396 		return (-1);
397 
398 	case ECKSUM:
399 		zfs_verror(hdl, EZFS_CKSUM, fmt, ap);
400 		return (-1);
401 	}
402 
403 	return (0);
404 }
405 
406 int
zfs_standard_error(libzfs_handle_t * hdl,int error,const char * msg)407 zfs_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
408 {
409 	return (zfs_standard_error_fmt(hdl, error, "%s", msg));
410 }
411 
412 /*PRINTFLIKE3*/
413 int
zfs_standard_error_fmt(libzfs_handle_t * hdl,int error,const char * fmt,...)414 zfs_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
415 {
416 	va_list ap;
417 
418 	va_start(ap, fmt);
419 
420 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
421 		va_end(ap);
422 		return (-1);
423 	}
424 
425 	switch (error) {
426 	case ENXIO:
427 	case ENODEV:
428 	case EPIPE:
429 		zfs_verror(hdl, EZFS_IO, fmt, ap);
430 		break;
431 
432 	case ENOENT:
433 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
434 		    "dataset does not exist"));
435 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
436 		break;
437 
438 	case ENOSPC:
439 	case EDQUOT:
440 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
441 		break;
442 
443 	case EEXIST:
444 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
445 		    "dataset already exists"));
446 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
447 		break;
448 
449 	case EBUSY:
450 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
451 		    "dataset is busy"));
452 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
453 		break;
454 	case EROFS:
455 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
456 		break;
457 	case ENAMETOOLONG:
458 		zfs_verror(hdl, EZFS_NAMETOOLONG, fmt, ap);
459 		break;
460 	case ENOTSUP:
461 		zfs_verror(hdl, EZFS_BADVERSION, fmt, ap);
462 		break;
463 	case EAGAIN:
464 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
465 		    "pool I/O is currently suspended"));
466 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
467 		break;
468 	case EREMOTEIO:
469 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
470 		break;
471 	case ZFS_ERR_UNKNOWN_SEND_STREAM_FEATURE:
472 	case ZFS_ERR_IOC_CMD_UNAVAIL:
473 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
474 		    "module does not support this operation. A reboot may "
475 		    "be required to enable this operation."));
476 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
477 		break;
478 	case ZFS_ERR_IOC_ARG_UNAVAIL:
479 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
480 		    "module does not support an option for this operation. "
481 		    "A reboot may be required to enable this option."));
482 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
483 		break;
484 	case ZFS_ERR_IOC_ARG_REQUIRED:
485 	case ZFS_ERR_IOC_ARG_BADTYPE:
486 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
487 		break;
488 	case ZFS_ERR_WRONG_PARENT:
489 		zfs_verror(hdl, EZFS_WRONG_PARENT, fmt, ap);
490 		break;
491 	case ZFS_ERR_BADPROP:
492 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
493 		break;
494 	default:
495 		zfs_error_aux(hdl, "%s", strerror(error));
496 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
497 		break;
498 	}
499 
500 	va_end(ap);
501 	return (-1);
502 }
503 
504 void
zfs_setprop_error(libzfs_handle_t * hdl,zfs_prop_t prop,int err,char * errbuf)505 zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
506     char *errbuf)
507 {
508 	switch (err) {
509 
510 	case ENOSPC:
511 		/*
512 		 * For quotas and reservations, ENOSPC indicates
513 		 * something different; setting a quota or reservation
514 		 * doesn't use any disk space.
515 		 */
516 		switch (prop) {
517 		case ZFS_PROP_QUOTA:
518 		case ZFS_PROP_REFQUOTA:
519 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
520 			    "size is less than current used or "
521 			    "reserved space"));
522 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
523 			break;
524 
525 		case ZFS_PROP_RESERVATION:
526 		case ZFS_PROP_REFRESERVATION:
527 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
528 			    "size is greater than available space"));
529 			(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
530 			break;
531 
532 		default:
533 			(void) zfs_standard_error(hdl, err, errbuf);
534 			break;
535 		}
536 		break;
537 
538 	case EBUSY:
539 		(void) zfs_standard_error(hdl, EBUSY, errbuf);
540 		break;
541 
542 	case EROFS:
543 		(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
544 		break;
545 
546 	case E2BIG:
547 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
548 		    "property value too long"));
549 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
550 		break;
551 
552 	case ENOTSUP:
553 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
554 		    "pool and or dataset must be upgraded to set this "
555 		    "property or value"));
556 		(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
557 		break;
558 
559 	case ERANGE:
560 		if (prop == ZFS_PROP_COMPRESSION ||
561 		    prop == ZFS_PROP_DNODESIZE ||
562 		    prop == ZFS_PROP_RECORDSIZE) {
563 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
564 			    "property setting is not allowed on "
565 			    "bootable datasets"));
566 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
567 		} else if (prop == ZFS_PROP_CHECKSUM ||
568 		    prop == ZFS_PROP_DEDUP) {
569 			(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
570 			    "property setting is not allowed on "
571 			    "root pools"));
572 			(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
573 		} else {
574 			(void) zfs_standard_error(hdl, err, errbuf);
575 		}
576 		break;
577 
578 	case EINVAL:
579 		if (prop == ZPROP_INVAL) {
580 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
581 		} else {
582 			(void) zfs_standard_error(hdl, err, errbuf);
583 		}
584 		break;
585 
586 	case ZFS_ERR_BADPROP:
587 		(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
588 		break;
589 
590 	case EACCES:
591 		if (prop == ZFS_PROP_KEYLOCATION) {
592 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
593 			    "keylocation may only be set on encryption roots"));
594 			(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
595 		} else {
596 			(void) zfs_standard_error(hdl, err, errbuf);
597 		}
598 		break;
599 
600 	case EOVERFLOW:
601 		/*
602 		 * This platform can't address a volume this big.
603 		 */
604 #ifdef _ILP32
605 		if (prop == ZFS_PROP_VOLSIZE) {
606 			(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
607 			break;
608 		}
609 #endif
610 		fallthrough;
611 	default:
612 		(void) zfs_standard_error(hdl, err, errbuf);
613 	}
614 }
615 
616 int
zpool_standard_error(libzfs_handle_t * hdl,int error,const char * msg)617 zpool_standard_error(libzfs_handle_t *hdl, int error, const char *msg)
618 {
619 	return (zpool_standard_error_fmt(hdl, error, "%s", msg));
620 }
621 
622 /*PRINTFLIKE3*/
623 int
zpool_standard_error_fmt(libzfs_handle_t * hdl,int error,const char * fmt,...)624 zpool_standard_error_fmt(libzfs_handle_t *hdl, int error, const char *fmt, ...)
625 {
626 	va_list ap;
627 
628 	va_start(ap, fmt);
629 
630 	if (zfs_common_error(hdl, error, fmt, ap) != 0) {
631 		va_end(ap);
632 		return (-1);
633 	}
634 
635 	switch (error) {
636 	case ENODEV:
637 		zfs_verror(hdl, EZFS_NODEVICE, fmt, ap);
638 		break;
639 
640 	case ENOENT:
641 		zfs_error_aux(hdl,
642 		    dgettext(TEXT_DOMAIN, "no such pool or dataset"));
643 		zfs_verror(hdl, EZFS_NOENT, fmt, ap);
644 		break;
645 
646 	case EEXIST:
647 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
648 		    "pool already exists"));
649 		zfs_verror(hdl, EZFS_EXISTS, fmt, ap);
650 		break;
651 
652 	case EBUSY:
653 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "pool is busy"));
654 		zfs_verror(hdl, EZFS_BUSY, fmt, ap);
655 		break;
656 
657 	/* There is no pending operation to cancel */
658 	case ENOTACTIVE:
659 		zfs_verror(hdl, EZFS_NO_PENDING, fmt, ap);
660 		break;
661 
662 	case ENXIO:
663 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
664 		    "one or more devices is currently unavailable"));
665 		zfs_verror(hdl, EZFS_BADDEV, fmt, ap);
666 		break;
667 
668 	case ENAMETOOLONG:
669 		zfs_verror(hdl, EZFS_DEVOVERFLOW, fmt, ap);
670 		break;
671 
672 	case ENOTSUP:
673 		zfs_verror(hdl, EZFS_POOL_NOTSUP, fmt, ap);
674 		break;
675 
676 	case EINVAL:
677 		zfs_verror(hdl, EZFS_POOL_INVALARG, fmt, ap);
678 		break;
679 
680 	case ENOSPC:
681 	case EDQUOT:
682 		zfs_verror(hdl, EZFS_NOSPC, fmt, ap);
683 		break;
684 
685 	case EAGAIN:
686 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
687 		    "pool I/O is currently suspended"));
688 		zfs_verror(hdl, EZFS_POOLUNAVAIL, fmt, ap);
689 		break;
690 
691 	case EROFS:
692 		zfs_verror(hdl, EZFS_POOLREADONLY, fmt, ap);
693 		break;
694 	case EDOM:
695 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
696 		    "block size out of range or does not match"));
697 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
698 		break;
699 	case EREMOTEIO:
700 		zfs_verror(hdl, EZFS_ACTIVE_POOL, fmt, ap);
701 		break;
702 	case ZFS_ERR_CHECKPOINT_EXISTS:
703 		zfs_verror(hdl, EZFS_CHECKPOINT_EXISTS, fmt, ap);
704 		break;
705 	case ZFS_ERR_DISCARDING_CHECKPOINT:
706 		zfs_verror(hdl, EZFS_DISCARDING_CHECKPOINT, fmt, ap);
707 		break;
708 	case ZFS_ERR_NO_CHECKPOINT:
709 		zfs_verror(hdl, EZFS_NO_CHECKPOINT, fmt, ap);
710 		break;
711 	case ZFS_ERR_DEVRM_IN_PROGRESS:
712 		zfs_verror(hdl, EZFS_DEVRM_IN_PROGRESS, fmt, ap);
713 		break;
714 	case ZFS_ERR_VDEV_TOO_BIG:
715 		zfs_verror(hdl, EZFS_VDEV_TOO_BIG, fmt, ap);
716 		break;
717 	case ZFS_ERR_EXPORT_IN_PROGRESS:
718 		zfs_verror(hdl, EZFS_EXPORT_IN_PROGRESS, fmt, ap);
719 		break;
720 	case ZFS_ERR_RESILVER_IN_PROGRESS:
721 		zfs_verror(hdl, EZFS_RESILVERING, fmt, ap);
722 		break;
723 	case ZFS_ERR_REBUILD_IN_PROGRESS:
724 		zfs_verror(hdl, EZFS_REBUILDING, fmt, ap);
725 		break;
726 	case ZFS_ERR_BADPROP:
727 		zfs_verror(hdl, EZFS_BADPROP, fmt, ap);
728 		break;
729 	case ZFS_ERR_IOC_CMD_UNAVAIL:
730 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
731 		    "module does not support this operation. A reboot may "
732 		    "be required to enable this operation."));
733 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
734 		break;
735 	case ZFS_ERR_IOC_ARG_UNAVAIL:
736 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "the loaded zfs "
737 		    "module does not support an option for this operation. "
738 		    "A reboot may be required to enable this option."));
739 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
740 		break;
741 	case ZFS_ERR_IOC_ARG_REQUIRED:
742 	case ZFS_ERR_IOC_ARG_BADTYPE:
743 		zfs_verror(hdl, EZFS_IOC_NOTSUPPORTED, fmt, ap);
744 		break;
745 	default:
746 		zfs_error_aux(hdl, "%s", strerror(error));
747 		zfs_verror(hdl, EZFS_UNKNOWN, fmt, ap);
748 	}
749 
750 	va_end(ap);
751 	return (-1);
752 }
753 
754 /*
755  * Display an out of memory error message and abort the current program.
756  */
757 int
no_memory(libzfs_handle_t * hdl)758 no_memory(libzfs_handle_t *hdl)
759 {
760 	return (zfs_error(hdl, EZFS_NOMEM, "internal error"));
761 }
762 
763 /*
764  * A safe form of malloc() which will die if the allocation fails.
765  */
766 void *
zfs_alloc(libzfs_handle_t * hdl,size_t size)767 zfs_alloc(libzfs_handle_t *hdl, size_t size)
768 {
769 	void *data;
770 
771 	if ((data = calloc(1, size)) == NULL)
772 		(void) no_memory(hdl);
773 
774 	return (data);
775 }
776 
777 /*
778  * A safe form of asprintf() which will die if the allocation fails.
779  */
780 /*PRINTFLIKE2*/
781 char *
zfs_asprintf(libzfs_handle_t * hdl,const char * fmt,...)782 zfs_asprintf(libzfs_handle_t *hdl, const char *fmt, ...)
783 {
784 	va_list ap;
785 	char *ret;
786 	int err;
787 
788 	va_start(ap, fmt);
789 
790 	err = vasprintf(&ret, fmt, ap);
791 
792 	va_end(ap);
793 
794 	if (err < 0) {
795 		(void) no_memory(hdl);
796 		ret = NULL;
797 	}
798 
799 	return (ret);
800 }
801 
802 /*
803  * A safe form of realloc(), which also zeroes newly allocated space.
804  */
805 void *
zfs_realloc(libzfs_handle_t * hdl,void * ptr,size_t oldsize,size_t newsize)806 zfs_realloc(libzfs_handle_t *hdl, void *ptr, size_t oldsize, size_t newsize)
807 {
808 	void *ret;
809 
810 	if ((ret = realloc(ptr, newsize)) == NULL) {
811 		(void) no_memory(hdl);
812 		return (NULL);
813 	}
814 
815 	bzero((char *)ret + oldsize, (newsize - oldsize));
816 	return (ret);
817 }
818 
819 /*
820  * A safe form of strdup() which will die if the allocation fails.
821  */
822 char *
zfs_strdup(libzfs_handle_t * hdl,const char * str)823 zfs_strdup(libzfs_handle_t *hdl, const char *str)
824 {
825 	char *ret;
826 
827 	if ((ret = strdup(str)) == NULL)
828 		(void) no_memory(hdl);
829 
830 	return (ret);
831 }
832 
833 void
libzfs_print_on_error(libzfs_handle_t * hdl,boolean_t printerr)834 libzfs_print_on_error(libzfs_handle_t *hdl, boolean_t printerr)
835 {
836 	hdl->libzfs_printerr = printerr;
837 }
838 
839 /*
840  * Read lines from an open file descriptor and store them in an array of
841  * strings until EOF.  lines[] will be allocated and populated with all the
842  * lines read.  All newlines are replaced with NULL terminators for
843  * convenience.  lines[] must be freed after use with libzfs_free_str_array().
844  *
845  * Returns the number of lines read.
846  */
847 static int
libzfs_read_stdout_from_fd(int fd,char ** lines[])848 libzfs_read_stdout_from_fd(int fd, char **lines[])
849 {
850 
851 	FILE *fp;
852 	int lines_cnt = 0;
853 	size_t len = 0;
854 	char *line = NULL;
855 	char **tmp_lines = NULL, **tmp;
856 	char *nl = NULL;
857 	int rc;
858 
859 	fp = fdopen(fd, "r");
860 	if (fp == NULL)
861 		return (0);
862 	while (1) {
863 		rc = getline(&line, &len, fp);
864 		if (rc == -1)
865 			break;
866 
867 		tmp = realloc(tmp_lines, sizeof (*tmp_lines) * (lines_cnt + 1));
868 		if (tmp == NULL) {
869 			/* Return the lines we were able to process */
870 			break;
871 		}
872 		tmp_lines = tmp;
873 
874 		/* Terminate newlines */
875 		if ((nl = strchr(line, '\n')) != NULL)
876 			*nl = '\0';
877 		tmp_lines[lines_cnt] = line;
878 		lines_cnt++;
879 		line = NULL;
880 	}
881 	fclose(fp);
882 	*lines = tmp_lines;
883 	return (lines_cnt);
884 }
885 
886 static int
libzfs_run_process_impl(const char * path,char * argv[],char * env[],int flags,char ** lines[],int * lines_cnt)887 libzfs_run_process_impl(const char *path, char *argv[], char *env[], int flags,
888     char **lines[], int *lines_cnt)
889 {
890 	pid_t pid;
891 	int error, devnull_fd;
892 	int link[2];
893 
894 	/*
895 	 * Setup a pipe between our child and parent process if we're
896 	 * reading stdout.
897 	 */
898 	if ((lines != NULL) && pipe2(link, O_CLOEXEC) == -1)
899 		return (-EPIPE);
900 
901 	pid = vfork();
902 	if (pid == 0) {
903 		/* Child process */
904 		devnull_fd = open("/dev/null", O_WRONLY | O_CLOEXEC);
905 
906 		if (devnull_fd < 0)
907 			_exit(-1);
908 
909 		if (!(flags & STDOUT_VERBOSE) && (lines == NULL))
910 			(void) dup2(devnull_fd, STDOUT_FILENO);
911 		else if (lines != NULL) {
912 			/* Save the output to lines[] */
913 			dup2(link[1], STDOUT_FILENO);
914 		}
915 
916 		if (!(flags & STDERR_VERBOSE))
917 			(void) dup2(devnull_fd, STDERR_FILENO);
918 
919 		if (flags & NO_DEFAULT_PATH) {
920 			if (env == NULL)
921 				execv(path, argv);
922 			else
923 				execve(path, argv, env);
924 		} else {
925 			if (env == NULL)
926 				execvp(path, argv);
927 			else
928 				execvpe(path, argv, env);
929 		}
930 
931 		_exit(-1);
932 	} else if (pid > 0) {
933 		/* Parent process */
934 		int status;
935 
936 		while ((error = waitpid(pid, &status, 0)) == -1 &&
937 		    errno == EINTR) { }
938 		if (error < 0 || !WIFEXITED(status))
939 			return (-1);
940 
941 		if (lines != NULL) {
942 			close(link[1]);
943 			*lines_cnt = libzfs_read_stdout_from_fd(link[0], lines);
944 		}
945 		return (WEXITSTATUS(status));
946 	}
947 
948 	return (-1);
949 }
950 
951 int
libzfs_run_process(const char * path,char * argv[],int flags)952 libzfs_run_process(const char *path, char *argv[], int flags)
953 {
954 	return (libzfs_run_process_impl(path, argv, NULL, flags, NULL, NULL));
955 }
956 
957 /*
958  * Run a command and store its stdout lines in an array of strings (lines[]).
959  * lines[] is allocated and populated for you, and the number of lines is set in
960  * lines_cnt.  lines[] must be freed after use with libzfs_free_str_array().
961  * All newlines (\n) in lines[] are terminated for convenience.
962  */
963 int
libzfs_run_process_get_stdout(const char * path,char * argv[],char * env[],char ** lines[],int * lines_cnt)964 libzfs_run_process_get_stdout(const char *path, char *argv[], char *env[],
965     char **lines[], int *lines_cnt)
966 {
967 	return (libzfs_run_process_impl(path, argv, env, 0, lines, lines_cnt));
968 }
969 
970 /*
971  * Same as libzfs_run_process_get_stdout(), but run without $PATH set.  This
972  * means that *path needs to be the full path to the executable.
973  */
974 int
libzfs_run_process_get_stdout_nopath(const char * path,char * argv[],char * env[],char ** lines[],int * lines_cnt)975 libzfs_run_process_get_stdout_nopath(const char *path, char *argv[],
976     char *env[], char **lines[], int *lines_cnt)
977 {
978 	return (libzfs_run_process_impl(path, argv, env, NO_DEFAULT_PATH,
979 	    lines, lines_cnt));
980 }
981 
982 /*
983  * Free an array of strings.  Free both the strings contained in the array and
984  * the array itself.
985  */
986 void
libzfs_free_str_array(char ** strs,int count)987 libzfs_free_str_array(char **strs, int count)
988 {
989 	while (--count >= 0)
990 		free(strs[count]);
991 
992 	free(strs);
993 }
994 
995 /*
996  * Returns 1 if environment variable is set to "YES", "yes", "ON", "on", or
997  * a non-zero number.
998  *
999  * Returns 0 otherwise.
1000  */
1001 int
libzfs_envvar_is_set(char * envvar)1002 libzfs_envvar_is_set(char *envvar)
1003 {
1004 	char *env = getenv(envvar);
1005 	if (env && (strtoul(env, NULL, 0) > 0 ||
1006 	    (!strncasecmp(env, "YES", 3) && strnlen(env, 4) == 3) ||
1007 	    (!strncasecmp(env, "ON", 2) && strnlen(env, 3) == 2)))
1008 		return (1);
1009 
1010 	return (0);
1011 }
1012 
1013 libzfs_handle_t *
libzfs_init(void)1014 libzfs_init(void)
1015 {
1016 	libzfs_handle_t *hdl;
1017 	int error;
1018 	char *env;
1019 
1020 	if ((error = libzfs_load_module()) != 0) {
1021 		errno = error;
1022 		return (NULL);
1023 	}
1024 
1025 	if ((hdl = calloc(1, sizeof (libzfs_handle_t))) == NULL) {
1026 		return (NULL);
1027 	}
1028 
1029 	if (regcomp(&hdl->libzfs_urire, URI_REGEX, 0) != 0) {
1030 		free(hdl);
1031 		return (NULL);
1032 	}
1033 
1034 	if ((hdl->libzfs_fd = open(ZFS_DEV, O_RDWR|O_EXCL|O_CLOEXEC)) < 0) {
1035 		free(hdl);
1036 		return (NULL);
1037 	}
1038 
1039 #ifdef HAVE_SETMNTENT
1040 	if ((hdl->libzfs_mnttab = setmntent(MNTTAB, "re")) == NULL) {
1041 #else
1042 	if ((hdl->libzfs_mnttab = fopen(MNTTAB, "re")) == NULL) {
1043 #endif
1044 		(void) close(hdl->libzfs_fd);
1045 		free(hdl);
1046 		return (NULL);
1047 	}
1048 
1049 	if (libzfs_core_init() != 0) {
1050 		(void) close(hdl->libzfs_fd);
1051 		(void) fclose(hdl->libzfs_mnttab);
1052 		free(hdl);
1053 		return (NULL);
1054 	}
1055 
1056 	zfs_prop_init();
1057 	zpool_prop_init();
1058 	zpool_feature_init();
1059 	libzfs_mnttab_init(hdl);
1060 	fletcher_4_init();
1061 
1062 	if (getenv("ZFS_PROP_DEBUG") != NULL) {
1063 		hdl->libzfs_prop_debug = B_TRUE;
1064 	}
1065 	if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1066 		if ((error = zfs_nicestrtonum(hdl, env,
1067 		    &hdl->libzfs_max_nvlist))) {
1068 			errno = error;
1069 			(void) close(hdl->libzfs_fd);
1070 			(void) fclose(hdl->libzfs_mnttab);
1071 			free(hdl);
1072 			return (NULL);
1073 		}
1074 	} else {
1075 		hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1076 	}
1077 
1078 	/*
1079 	 * For testing, remove some settable properties and features
1080 	 */
1081 	if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1082 		zprop_desc_t *proptbl;
1083 
1084 		proptbl = zpool_prop_get_table();
1085 		proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1086 
1087 		proptbl = zfs_prop_get_table();
1088 		proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1089 
1090 		zfeature_info_t *ftbl = spa_feature_table;
1091 		ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1092 	}
1093 
1094 	return (hdl);
1095 }
1096 
1097 void
1098 libzfs_fini(libzfs_handle_t *hdl)
1099 {
1100 	(void) close(hdl->libzfs_fd);
1101 	if (hdl->libzfs_mnttab)
1102 #ifdef HAVE_SETMNTENT
1103 		(void) endmntent(hdl->libzfs_mnttab);
1104 #else
1105 		(void) fclose(hdl->libzfs_mnttab);
1106 #endif
1107 	zpool_free_handles(hdl);
1108 	namespace_clear(hdl);
1109 	libzfs_mnttab_fini(hdl);
1110 	libzfs_core_fini();
1111 	regfree(&hdl->libzfs_urire);
1112 	fletcher_4_fini();
1113 #if LIBFETCH_DYNAMIC
1114 	if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1115 		(void) dlclose(hdl->libfetch);
1116 	free(hdl->libfetch_load_error);
1117 #endif
1118 	free(hdl);
1119 }
1120 
1121 libzfs_handle_t *
1122 zpool_get_handle(zpool_handle_t *zhp)
1123 {
1124 	return (zhp->zpool_hdl);
1125 }
1126 
1127 libzfs_handle_t *
1128 zfs_get_handle(zfs_handle_t *zhp)
1129 {
1130 	return (zhp->zfs_hdl);
1131 }
1132 
1133 zpool_handle_t *
1134 zfs_get_pool_handle(const zfs_handle_t *zhp)
1135 {
1136 	return (zhp->zpool_hdl);
1137 }
1138 
1139 /*
1140  * Given a name, determine whether or not it's a valid path
1141  * (starts with '/' or "./").  If so, walk the mnttab trying
1142  * to match the device number.  If not, treat the path as an
1143  * fs/vol/snap/bkmark name.
1144  */
1145 zfs_handle_t *
1146 zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
1147 {
1148 	struct stat64 statbuf;
1149 	struct extmnttab entry;
1150 
1151 	if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1152 		/*
1153 		 * It's not a valid path, assume it's a name of type 'argtype'.
1154 		 */
1155 		return (zfs_open(hdl, path, argtype));
1156 	}
1157 
1158 	/* Reopen MNTTAB to prevent reading stale data from open file */
1159 	if (freopen(MNTTAB, "re", hdl->libzfs_mnttab) == NULL)
1160 		return (NULL);
1161 
1162 	if (getextmntent(path, &entry, &statbuf) != 0)
1163 		return (NULL);
1164 
1165 	if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1166 		(void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1167 		    path);
1168 		return (NULL);
1169 	}
1170 
1171 	return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1172 }
1173 
1174 /*
1175  * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1176  * an ioctl().
1177  */
1178 int
1179 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1180 {
1181 	if (len == 0)
1182 		len = 256 * 1024;
1183 	zc->zc_nvlist_dst_size = len;
1184 	zc->zc_nvlist_dst =
1185 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1186 	if (zc->zc_nvlist_dst == 0)
1187 		return (-1);
1188 
1189 	return (0);
1190 }
1191 
1192 /*
1193  * Called when an ioctl() which returns an nvlist fails with ENOMEM.  This will
1194  * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1195  * filled in by the kernel to indicate the actual required size.
1196  */
1197 int
1198 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1199 {
1200 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1201 	zc->zc_nvlist_dst =
1202 	    (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1203 	if (zc->zc_nvlist_dst == 0)
1204 		return (-1);
1205 
1206 	return (0);
1207 }
1208 
1209 /*
1210  * Called to free the src and dst nvlists stored in the command structure.
1211  */
1212 void
1213 zcmd_free_nvlists(zfs_cmd_t *zc)
1214 {
1215 	free((void *)(uintptr_t)zc->zc_nvlist_conf);
1216 	free((void *)(uintptr_t)zc->zc_nvlist_src);
1217 	free((void *)(uintptr_t)zc->zc_nvlist_dst);
1218 	zc->zc_nvlist_conf = 0;
1219 	zc->zc_nvlist_src = 0;
1220 	zc->zc_nvlist_dst = 0;
1221 }
1222 
1223 static int
1224 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1225     nvlist_t *nvl)
1226 {
1227 	char *packed;
1228 	size_t len;
1229 
1230 	verify(nvlist_size(nvl, &len, NV_ENCODE_NATIVE) == 0);
1231 
1232 	if ((packed = zfs_alloc(hdl, len)) == NULL)
1233 		return (-1);
1234 
1235 	verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1236 
1237 	*outnv = (uint64_t)(uintptr_t)packed;
1238 	*outlen = len;
1239 
1240 	return (0);
1241 }
1242 
1243 int
1244 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1245 {
1246 	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1247 	    &zc->zc_nvlist_conf_size, nvl));
1248 }
1249 
1250 int
1251 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1252 {
1253 	return (zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1254 	    &zc->zc_nvlist_src_size, nvl));
1255 }
1256 
1257 /*
1258  * Unpacks an nvlist from the ZFS ioctl command structure.
1259  */
1260 int
1261 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1262 {
1263 	if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1264 	    zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1265 		return (no_memory(hdl));
1266 
1267 	return (0);
1268 }
1269 
1270 /*
1271  * ================================================================
1272  * API shared by zfs and zpool property management
1273  * ================================================================
1274  */
1275 
1276 static void
1277 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1278 {
1279 	zprop_list_t *pl = cbp->cb_proplist;
1280 	int i;
1281 	char *title;
1282 	size_t len;
1283 
1284 	cbp->cb_first = B_FALSE;
1285 	if (cbp->cb_scripted)
1286 		return;
1287 
1288 	/*
1289 	 * Start with the length of the column headers.
1290 	 */
1291 	cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1292 	cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1293 	    "PROPERTY"));
1294 	cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1295 	    "VALUE"));
1296 	cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1297 	    "RECEIVED"));
1298 	cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1299 	    "SOURCE"));
1300 
1301 	/* first property is always NAME */
1302 	assert(cbp->cb_proplist->pl_prop ==
1303 	    ((type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME : ZFS_PROP_NAME));
1304 
1305 	/*
1306 	 * Go through and calculate the widths for each column.  For the
1307 	 * 'source' column, we kludge it up by taking the worst-case scenario of
1308 	 * inheriting from the longest name.  This is acceptable because in the
1309 	 * majority of cases 'SOURCE' is the last column displayed, and we don't
1310 	 * use the width anyway.  Note that the 'VALUE' column can be oversized,
1311 	 * if the name of the property is much longer than any values we find.
1312 	 */
1313 	for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1314 		/*
1315 		 * 'PROPERTY' column
1316 		 */
1317 		if (pl->pl_prop != ZPROP_INVAL) {
1318 			const char *propname = (type == ZFS_TYPE_POOL) ?
1319 			    zpool_prop_to_name(pl->pl_prop) :
1320 			    zfs_prop_to_name(pl->pl_prop);
1321 
1322 			len = strlen(propname);
1323 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1324 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1325 		} else {
1326 			len = strlen(pl->pl_user_prop);
1327 			if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1328 				cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1329 		}
1330 
1331 		/*
1332 		 * 'VALUE' column.  The first property is always the 'name'
1333 		 * property that was tacked on either by /sbin/zfs's
1334 		 * zfs_do_get() or when calling zprop_expand_list(), so we
1335 		 * ignore its width.  If the user specified the name property
1336 		 * to display, then it will be later in the list in any case.
1337 		 */
1338 		if (pl != cbp->cb_proplist &&
1339 		    pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1340 			cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1341 
1342 		/* 'RECEIVED' column. */
1343 		if (pl != cbp->cb_proplist &&
1344 		    pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1345 			cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1346 
1347 		/*
1348 		 * 'NAME' and 'SOURCE' columns
1349 		 */
1350 		if (pl->pl_prop == (type == ZFS_TYPE_POOL ? ZPOOL_PROP_NAME :
1351 		    ZFS_PROP_NAME) &&
1352 		    pl->pl_width > cbp->cb_colwidths[GET_COL_NAME]) {
1353 			cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1354 			cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1355 			    strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1356 		}
1357 	}
1358 
1359 	/*
1360 	 * Now go through and print the headers.
1361 	 */
1362 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1363 		switch (cbp->cb_columns[i]) {
1364 		case GET_COL_NAME:
1365 			title = dgettext(TEXT_DOMAIN, "NAME");
1366 			break;
1367 		case GET_COL_PROPERTY:
1368 			title = dgettext(TEXT_DOMAIN, "PROPERTY");
1369 			break;
1370 		case GET_COL_VALUE:
1371 			title = dgettext(TEXT_DOMAIN, "VALUE");
1372 			break;
1373 		case GET_COL_RECVD:
1374 			title = dgettext(TEXT_DOMAIN, "RECEIVED");
1375 			break;
1376 		case GET_COL_SOURCE:
1377 			title = dgettext(TEXT_DOMAIN, "SOURCE");
1378 			break;
1379 		default:
1380 			title = NULL;
1381 		}
1382 
1383 		if (title != NULL) {
1384 			if (i == (ZFS_GET_NCOLS - 1) ||
1385 			    cbp->cb_columns[i + 1] == GET_COL_NONE)
1386 				(void) printf("%s", title);
1387 			else
1388 				(void) printf("%-*s  ",
1389 				    cbp->cb_colwidths[cbp->cb_columns[i]],
1390 				    title);
1391 		}
1392 	}
1393 	(void) printf("\n");
1394 }
1395 
1396 /*
1397  * Display a single line of output, according to the settings in the callback
1398  * structure.
1399  */
1400 void
1401 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1402     const char *propname, const char *value, zprop_source_t sourcetype,
1403     const char *source, const char *recvd_value)
1404 {
1405 	int i;
1406 	const char *str = NULL;
1407 	char buf[128];
1408 
1409 	/*
1410 	 * Ignore those source types that the user has chosen to ignore.
1411 	 */
1412 	if ((sourcetype & cbp->cb_sources) == 0)
1413 		return;
1414 
1415 	if (cbp->cb_first)
1416 		zprop_print_headers(cbp, cbp->cb_type);
1417 
1418 	for (i = 0; i < ZFS_GET_NCOLS; i++) {
1419 		switch (cbp->cb_columns[i]) {
1420 		case GET_COL_NAME:
1421 			str = name;
1422 			break;
1423 
1424 		case GET_COL_PROPERTY:
1425 			str = propname;
1426 			break;
1427 
1428 		case GET_COL_VALUE:
1429 			str = value;
1430 			break;
1431 
1432 		case GET_COL_SOURCE:
1433 			switch (sourcetype) {
1434 			case ZPROP_SRC_NONE:
1435 				str = "-";
1436 				break;
1437 
1438 			case ZPROP_SRC_DEFAULT:
1439 				str = "default";
1440 				break;
1441 
1442 			case ZPROP_SRC_LOCAL:
1443 				str = "local";
1444 				break;
1445 
1446 			case ZPROP_SRC_TEMPORARY:
1447 				str = "temporary";
1448 				break;
1449 
1450 			case ZPROP_SRC_INHERITED:
1451 				(void) snprintf(buf, sizeof (buf),
1452 				    "inherited from %s", source);
1453 				str = buf;
1454 				break;
1455 			case ZPROP_SRC_RECEIVED:
1456 				str = "received";
1457 				break;
1458 
1459 			default:
1460 				str = NULL;
1461 				assert(!"unhandled zprop_source_t");
1462 			}
1463 			break;
1464 
1465 		case GET_COL_RECVD:
1466 			str = (recvd_value == NULL ? "-" : recvd_value);
1467 			break;
1468 
1469 		default:
1470 			continue;
1471 		}
1472 
1473 		if (i == (ZFS_GET_NCOLS - 1) ||
1474 		    cbp->cb_columns[i + 1] == GET_COL_NONE)
1475 			(void) printf("%s", str);
1476 		else if (cbp->cb_scripted)
1477 			(void) printf("%s\t", str);
1478 		else
1479 			(void) printf("%-*s  ",
1480 			    cbp->cb_colwidths[cbp->cb_columns[i]],
1481 			    str);
1482 	}
1483 
1484 	(void) printf("\n");
1485 }
1486 
1487 /*
1488  * Given a numeric suffix, convert the value into a number of bits that the
1489  * resulting value must be shifted.
1490  */
1491 static int
1492 str2shift(libzfs_handle_t *hdl, const char *buf)
1493 {
1494 	const char *ends = "BKMGTPEZ";
1495 	int i;
1496 
1497 	if (buf[0] == '\0')
1498 		return (0);
1499 	for (i = 0; i < strlen(ends); i++) {
1500 		if (toupper(buf[0]) == ends[i])
1501 			break;
1502 	}
1503 	if (i == strlen(ends)) {
1504 		if (hdl)
1505 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1506 			    "invalid numeric suffix '%s'"), buf);
1507 		return (-1);
1508 	}
1509 
1510 	/*
1511 	 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1512 	 * However, 'BB' and 'BiB' are disallowed.
1513 	 */
1514 	if (buf[1] == '\0' ||
1515 	    (toupper(buf[0]) != 'B' &&
1516 	    ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1517 	    (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1518 	    buf[3] == '\0'))))
1519 		return (10 * i);
1520 
1521 	if (hdl)
1522 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1523 		    "invalid numeric suffix '%s'"), buf);
1524 	return (-1);
1525 }
1526 
1527 /*
1528  * Convert a string of the form '100G' into a real number.  Used when setting
1529  * properties or creating a volume.  'buf' is used to place an extended error
1530  * message for the caller to use.
1531  */
1532 int
1533 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1534 {
1535 	char *end;
1536 	int shift;
1537 
1538 	*num = 0;
1539 
1540 	/* Check to see if this looks like a number.  */
1541 	if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1542 		if (hdl)
1543 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1544 			    "bad numeric value '%s'"), value);
1545 		return (-1);
1546 	}
1547 
1548 	/* Rely on strtoull() to process the numeric portion.  */
1549 	errno = 0;
1550 	*num = strtoull(value, &end, 10);
1551 
1552 	/*
1553 	 * Check for ERANGE, which indicates that the value is too large to fit
1554 	 * in a 64-bit value.
1555 	 */
1556 	if (errno == ERANGE) {
1557 		if (hdl)
1558 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1559 			    "numeric value is too large"));
1560 		return (-1);
1561 	}
1562 
1563 	/*
1564 	 * If we have a decimal value, then do the computation with floating
1565 	 * point arithmetic.  Otherwise, use standard arithmetic.
1566 	 */
1567 	if (*end == '.') {
1568 		double fval = strtod(value, &end);
1569 
1570 		if ((shift = str2shift(hdl, end)) == -1)
1571 			return (-1);
1572 
1573 		fval *= pow(2, shift);
1574 
1575 		/*
1576 		 * UINT64_MAX is not exactly representable as a double.
1577 		 * The closest representation is UINT64_MAX + 1, so we
1578 		 * use a >= comparison instead of > for the bounds check.
1579 		 */
1580 		if (fval >= (double)UINT64_MAX) {
1581 			if (hdl)
1582 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1583 				    "numeric value is too large"));
1584 			return (-1);
1585 		}
1586 
1587 		*num = (uint64_t)fval;
1588 	} else {
1589 		if ((shift = str2shift(hdl, end)) == -1)
1590 			return (-1);
1591 
1592 		/* Check for overflow */
1593 		if (shift >= 64 || (*num << shift) >> shift != *num) {
1594 			if (hdl)
1595 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1596 				    "numeric value is too large"));
1597 			return (-1);
1598 		}
1599 
1600 		*num <<= shift;
1601 	}
1602 
1603 	return (0);
1604 }
1605 
1606 /*
1607  * Given a propname=value nvpair to set, parse any numeric properties
1608  * (index, boolean, etc) if they are specified as strings and add the
1609  * resulting nvpair to the returned nvlist.
1610  *
1611  * At the DSL layer, all properties are either 64-bit numbers or strings.
1612  * We want the user to be able to ignore this fact and specify properties
1613  * as native values (numbers, for example) or as strings (to simplify
1614  * command line utilities).  This also handles converting index types
1615  * (compression, checksum, etc) from strings to their on-disk index.
1616  */
1617 int
1618 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1619     zfs_type_t type, nvlist_t *ret, char **svalp, uint64_t *ivalp,
1620     const char *errbuf)
1621 {
1622 	data_type_t datatype = nvpair_type(elem);
1623 	zprop_type_t proptype;
1624 	const char *propname;
1625 	char *value;
1626 	boolean_t isnone = B_FALSE;
1627 	boolean_t isauto = B_FALSE;
1628 	int err = 0;
1629 
1630 	if (type == ZFS_TYPE_POOL) {
1631 		proptype = zpool_prop_get_type(prop);
1632 		propname = zpool_prop_to_name(prop);
1633 	} else {
1634 		proptype = zfs_prop_get_type(prop);
1635 		propname = zfs_prop_to_name(prop);
1636 	}
1637 
1638 	/*
1639 	 * Convert any properties to the internal DSL value types.
1640 	 */
1641 	*svalp = NULL;
1642 	*ivalp = 0;
1643 
1644 	switch (proptype) {
1645 	case PROP_TYPE_STRING:
1646 		if (datatype != DATA_TYPE_STRING) {
1647 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1648 			    "'%s' must be a string"), nvpair_name(elem));
1649 			goto error;
1650 		}
1651 		err = nvpair_value_string(elem, svalp);
1652 		if (err != 0) {
1653 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1654 			    "'%s' is invalid"), nvpair_name(elem));
1655 			goto error;
1656 		}
1657 		if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1658 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1659 			    "'%s' is too long"), nvpair_name(elem));
1660 			goto error;
1661 		}
1662 		break;
1663 
1664 	case PROP_TYPE_NUMBER:
1665 		if (datatype == DATA_TYPE_STRING) {
1666 			(void) nvpair_value_string(elem, &value);
1667 			if (strcmp(value, "none") == 0) {
1668 				isnone = B_TRUE;
1669 			} else if (strcmp(value, "auto") == 0) {
1670 				isauto = B_TRUE;
1671 			} else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1672 				goto error;
1673 			}
1674 		} else if (datatype == DATA_TYPE_UINT64) {
1675 			(void) nvpair_value_uint64(elem, ivalp);
1676 		} else {
1677 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1678 			    "'%s' must be a number"), nvpair_name(elem));
1679 			goto error;
1680 		}
1681 
1682 		/*
1683 		 * Quota special: force 'none' and don't allow 0.
1684 		 */
1685 		if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1686 		    (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1687 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1688 			    "use 'none' to disable quota/refquota"));
1689 			goto error;
1690 		}
1691 
1692 		/*
1693 		 * Special handling for "*_limit=none". In this case it's not
1694 		 * 0 but UINT64_MAX.
1695 		 */
1696 		if ((type & ZFS_TYPE_DATASET) && isnone &&
1697 		    (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1698 		    prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1699 			*ivalp = UINT64_MAX;
1700 		}
1701 
1702 		/*
1703 		 * Special handling for setting 'refreservation' to 'auto'.  Use
1704 		 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1705 		 * 'auto' is only allowed on volumes.
1706 		 */
1707 		if (isauto) {
1708 			switch (prop) {
1709 			case ZFS_PROP_REFRESERVATION:
1710 				if ((type & ZFS_TYPE_VOLUME) == 0) {
1711 					zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1712 					    "'%s=auto' only allowed on "
1713 					    "volumes"), nvpair_name(elem));
1714 					goto error;
1715 				}
1716 				*ivalp = UINT64_MAX;
1717 				break;
1718 			default:
1719 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1720 				    "'auto' is invalid value for '%s'"),
1721 				    nvpair_name(elem));
1722 				goto error;
1723 			}
1724 		}
1725 
1726 		break;
1727 
1728 	case PROP_TYPE_INDEX:
1729 		if (datatype != DATA_TYPE_STRING) {
1730 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1731 			    "'%s' must be a string"), nvpair_name(elem));
1732 			goto error;
1733 		}
1734 
1735 		(void) nvpair_value_string(elem, &value);
1736 
1737 		if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1738 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1739 			    "'%s' must be one of '%s'"), propname,
1740 			    zprop_values(prop, type));
1741 			goto error;
1742 		}
1743 		break;
1744 
1745 	default:
1746 		abort();
1747 	}
1748 
1749 	/*
1750 	 * Add the result to our return set of properties.
1751 	 */
1752 	if (*svalp != NULL) {
1753 		if (nvlist_add_string(ret, propname, *svalp) != 0) {
1754 			(void) no_memory(hdl);
1755 			return (-1);
1756 		}
1757 	} else {
1758 		if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1759 			(void) no_memory(hdl);
1760 			return (-1);
1761 		}
1762 	}
1763 
1764 	return (0);
1765 error:
1766 	(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1767 	return (-1);
1768 }
1769 
1770 static int
1771 addlist(libzfs_handle_t *hdl, char *propname, zprop_list_t **listp,
1772     zfs_type_t type)
1773 {
1774 	int prop;
1775 	zprop_list_t *entry;
1776 
1777 	prop = zprop_name_to_prop(propname, type);
1778 
1779 	if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1780 		prop = ZPROP_INVAL;
1781 
1782 	/*
1783 	 * When no property table entry can be found, return failure if
1784 	 * this is a pool property or if this isn't a user-defined
1785 	 * dataset property,
1786 	 */
1787 	if (prop == ZPROP_INVAL && ((type == ZFS_TYPE_POOL &&
1788 	    !zpool_prop_feature(propname) &&
1789 	    !zpool_prop_unsupported(propname)) ||
1790 	    (type == ZFS_TYPE_DATASET && !zfs_prop_user(propname) &&
1791 	    !zfs_prop_userquota(propname) && !zfs_prop_written(propname)))) {
1792 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1793 		    "invalid property '%s'"), propname);
1794 		return (zfs_error(hdl, EZFS_BADPROP,
1795 		    dgettext(TEXT_DOMAIN, "bad property list")));
1796 	}
1797 
1798 	if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1799 		return (-1);
1800 
1801 	entry->pl_prop = prop;
1802 	if (prop == ZPROP_INVAL) {
1803 		if ((entry->pl_user_prop = zfs_strdup(hdl, propname)) ==
1804 		    NULL) {
1805 			free(entry);
1806 			return (-1);
1807 		}
1808 		entry->pl_width = strlen(propname);
1809 	} else {
1810 		entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1811 		    type);
1812 	}
1813 
1814 	*listp = entry;
1815 
1816 	return (0);
1817 }
1818 
1819 /*
1820  * Given a comma-separated list of properties, construct a property list
1821  * containing both user-defined and native properties.  This function will
1822  * return a NULL list if 'all' is specified, which can later be expanded
1823  * by zprop_expand_list().
1824  */
1825 int
1826 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1827     zfs_type_t type)
1828 {
1829 	*listp = NULL;
1830 
1831 	/*
1832 	 * If 'all' is specified, return a NULL list.
1833 	 */
1834 	if (strcmp(props, "all") == 0)
1835 		return (0);
1836 
1837 	/*
1838 	 * If no props were specified, return an error.
1839 	 */
1840 	if (props[0] == '\0') {
1841 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1842 		    "no properties specified"));
1843 		return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
1844 		    "bad property list")));
1845 	}
1846 
1847 	/*
1848 	 * It would be nice to use getsubopt() here, but the inclusion of column
1849 	 * aliases makes this more effort than it's worth.
1850 	 */
1851 	while (*props != '\0') {
1852 		size_t len;
1853 		char *p;
1854 		char c;
1855 
1856 		if ((p = strchr(props, ',')) == NULL) {
1857 			len = strlen(props);
1858 			p = props + len;
1859 		} else {
1860 			len = p - props;
1861 		}
1862 
1863 		/*
1864 		 * Check for empty options.
1865 		 */
1866 		if (len == 0) {
1867 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1868 			    "empty property name"));
1869 			return (zfs_error(hdl, EZFS_BADPROP,
1870 			    dgettext(TEXT_DOMAIN, "bad property list")));
1871 		}
1872 
1873 		/*
1874 		 * Check all regular property names.
1875 		 */
1876 		c = props[len];
1877 		props[len] = '\0';
1878 
1879 		if (strcmp(props, "space") == 0) {
1880 			static char *spaceprops[] = {
1881 				"name", "avail", "used", "usedbysnapshots",
1882 				"usedbydataset", "usedbyrefreservation",
1883 				"usedbychildren", NULL
1884 			};
1885 			int i;
1886 
1887 			for (i = 0; spaceprops[i]; i++) {
1888 				if (addlist(hdl, spaceprops[i], listp, type))
1889 					return (-1);
1890 				listp = &(*listp)->pl_next;
1891 			}
1892 		} else {
1893 			if (addlist(hdl, props, listp, type))
1894 				return (-1);
1895 			listp = &(*listp)->pl_next;
1896 		}
1897 
1898 		props = p;
1899 		if (c == ',')
1900 			props++;
1901 	}
1902 
1903 	return (0);
1904 }
1905 
1906 void
1907 zprop_free_list(zprop_list_t *pl)
1908 {
1909 	zprop_list_t *next;
1910 
1911 	while (pl != NULL) {
1912 		next = pl->pl_next;
1913 		free(pl->pl_user_prop);
1914 		free(pl);
1915 		pl = next;
1916 	}
1917 }
1918 
1919 typedef struct expand_data {
1920 	zprop_list_t	**last;
1921 	libzfs_handle_t	*hdl;
1922 	zfs_type_t type;
1923 } expand_data_t;
1924 
1925 static int
1926 zprop_expand_list_cb(int prop, void *cb)
1927 {
1928 	zprop_list_t *entry;
1929 	expand_data_t *edp = cb;
1930 
1931 	if ((entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t))) == NULL)
1932 		return (ZPROP_INVAL);
1933 
1934 	entry->pl_prop = prop;
1935 	entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
1936 	entry->pl_all = B_TRUE;
1937 
1938 	*(edp->last) = entry;
1939 	edp->last = &entry->pl_next;
1940 
1941 	return (ZPROP_CONT);
1942 }
1943 
1944 int
1945 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
1946 {
1947 	zprop_list_t *entry;
1948 	zprop_list_t **last;
1949 	expand_data_t exp;
1950 
1951 	if (*plp == NULL) {
1952 		/*
1953 		 * If this is the very first time we've been called for an 'all'
1954 		 * specification, expand the list to include all native
1955 		 * properties.
1956 		 */
1957 		last = plp;
1958 
1959 		exp.last = last;
1960 		exp.hdl = hdl;
1961 		exp.type = type;
1962 
1963 		if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
1964 		    B_FALSE, type) == ZPROP_INVAL)
1965 			return (-1);
1966 
1967 		/*
1968 		 * Add 'name' to the beginning of the list, which is handled
1969 		 * specially.
1970 		 */
1971 		if ((entry = zfs_alloc(hdl, sizeof (zprop_list_t))) == NULL)
1972 			return (-1);
1973 
1974 		entry->pl_prop = (type == ZFS_TYPE_POOL) ?  ZPOOL_PROP_NAME :
1975 		    ZFS_PROP_NAME;
1976 		entry->pl_width = zprop_width(entry->pl_prop,
1977 		    &entry->pl_fixed, type);
1978 		entry->pl_all = B_TRUE;
1979 		entry->pl_next = *plp;
1980 		*plp = entry;
1981 	}
1982 	return (0);
1983 }
1984 
1985 int
1986 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
1987     zfs_type_t type)
1988 {
1989 	return (zprop_iter_common(func, cb, show_all, ordered, type));
1990 }
1991 
1992 /*
1993  * Fill given version buffer with zfs userland version
1994  */
1995 void
1996 zfs_version_userland(char *version, int len)
1997 {
1998 	(void) strlcpy(version, ZFS_META_ALIAS, len);
1999 }
2000 
2001 /*
2002  * Prints both zfs userland and kernel versions
2003  * Returns 0 on success, and -1 on error (with errno set)
2004  */
2005 int
2006 zfs_version_print(void)
2007 {
2008 	char zver_userland[128];
2009 	char zver_kernel[128];
2010 
2011 	zfs_version_userland(zver_userland, sizeof (zver_userland));
2012 
2013 	(void) printf("%s\n", zver_userland);
2014 
2015 	if (zfs_version_kernel(zver_kernel, sizeof (zver_kernel)) == -1) {
2016 		fprintf(stderr, "zfs_version_kernel() failed: %s\n",
2017 		    strerror(errno));
2018 		return (-1);
2019 	}
2020 
2021 	(void) printf("zfs-kmod-%s\n", zver_kernel);
2022 
2023 	return (0);
2024 }
2025 
2026 /*
2027  * Return 1 if the user requested ANSI color output, and our terminal supports
2028  * it.  Return 0 for no color.
2029  */
2030 int
2031 use_color(void)
2032 {
2033 	static int use_color = -1;
2034 	char *term;
2035 
2036 	/*
2037 	 * Optimization:
2038 	 *
2039 	 * For each zpool invocation, we do a single check to see if we should
2040 	 * be using color or not, and cache that value for the lifetime of the
2041 	 * the zpool command.  That makes it cheap to call use_color() when
2042 	 * we're printing with color.  We assume that the settings are not going
2043 	 * to change during the invocation of a zpool command (the user isn't
2044 	 * going to change the ZFS_COLOR value while zpool is running, for
2045 	 * example).
2046 	 */
2047 	if (use_color != -1) {
2048 		/*
2049 		 * We've already figured out if we should be using color or
2050 		 * not.  Return the cached value.
2051 		 */
2052 		return (use_color);
2053 	}
2054 
2055 	term = getenv("TERM");
2056 	/*
2057 	 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
2058 	 * output.  However if NO_COLOR is set (https://no-color.org/) then
2059 	 * don't use it.  Also, don't use color if terminal doesn't support
2060 	 * it.
2061 	 */
2062 	if (libzfs_envvar_is_set("ZFS_COLOR") &&
2063 	    !libzfs_envvar_is_set("NO_COLOR") &&
2064 	    isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
2065 	    strcmp("unknown", term) != 0) {
2066 		/* Color supported */
2067 		use_color = 1;
2068 	} else {
2069 		use_color = 0;
2070 	}
2071 
2072 	return (use_color);
2073 }
2074 
2075 /*
2076  * The functions color_start() and color_end() are used for when you want
2077  * to colorize a block of text.
2078  *
2079  * For example:
2080  * color_start(ANSI_RED)
2081  * printf("hello");
2082  * printf("world");
2083  * color_end();
2084  */
2085 void
2086 color_start(const char *color)
2087 {
2088 	if (color && use_color()) {
2089 		fputs(color, stdout);
2090 		fflush(stdout);
2091 	}
2092 }
2093 
2094 void
2095 color_end(void)
2096 {
2097 	if (use_color()) {
2098 		fputs(ANSI_RESET, stdout);
2099 		fflush(stdout);
2100 	}
2101 }
2102 
2103 /*
2104  * printf() with a color. If color is NULL, then do a normal printf.
2105  */
2106 int
2107 printf_color(const char *color, char *format, ...)
2108 {
2109 	va_list aptr;
2110 	int rc;
2111 
2112 	if (color)
2113 		color_start(color);
2114 
2115 	va_start(aptr, format);
2116 	rc = vprintf(format, aptr);
2117 	va_end(aptr);
2118 
2119 	if (color)
2120 		color_end();
2121 
2122 	return (rc);
2123 }
2124 
2125 /* PATH + 5 env vars + a NULL entry = 7 */
2126 #define	ZPOOL_VDEV_SCRIPT_ENV_COUNT 7
2127 
2128 /*
2129  * There's a few places where ZFS will call external scripts (like the script
2130  * in zpool.d/ and `zfs_prepare_disk`).  These scripts are called with a
2131  * reduced $PATH, and some vdev specific environment vars set.  This function
2132  * will allocate an populate the environment variable array that is passed to
2133  * these scripts.  The user must free the arrays with zpool_vdev_free_env() when
2134  * they are done.
2135  *
2136  * The following env vars will be set (but value could be blank):
2137  *
2138  * POOL_NAME
2139  * VDEV_PATH
2140  * VDEV_UPATH
2141  * VDEV_ENC_SYSFS_PATH
2142  *
2143  * In addition, you can set an optional environment variable named 'opt_key'
2144  * to 'opt_val' if you want.
2145  *
2146  * Returns allocated env[] array on success, NULL otherwise.
2147  */
2148 char **
2149 zpool_vdev_script_alloc_env(const char *pool_name,
2150     const char *vdev_path, const char *vdev_upath,
2151     const char *vdev_enc_sysfs_path, const char *opt_key, const char *opt_val)
2152 {
2153 	char **env = NULL;
2154 	int rc;
2155 
2156 	env = calloc(ZPOOL_VDEV_SCRIPT_ENV_COUNT, sizeof (*env));
2157 	if (!env)
2158 		return (NULL);
2159 
2160 	env[0] = strdup("PATH=/bin:/sbin:/usr/bin:/usr/sbin");
2161 	if (!env[0])
2162 		goto error;
2163 
2164 	/* Setup our custom environment variables */
2165 	rc = asprintf(&env[1], "POOL_NAME=%s", pool_name ? pool_name : "");
2166 	if (rc == -1) {
2167 		env[1] = NULL;
2168 		goto error;
2169 	}
2170 
2171 	rc = asprintf(&env[2], "VDEV_PATH=%s", vdev_path ? vdev_path : "");
2172 	if (rc == -1) {
2173 		env[2] = NULL;
2174 		goto error;
2175 	}
2176 
2177 	rc = asprintf(&env[3], "VDEV_UPATH=%s", vdev_upath ? vdev_upath : "");
2178 	if (rc == -1) {
2179 		env[3] = NULL;
2180 		goto error;
2181 	}
2182 
2183 	rc = asprintf(&env[4], "VDEV_ENC_SYSFS_PATH=%s",
2184 	    vdev_enc_sysfs_path ?  vdev_enc_sysfs_path : "");
2185 	if (rc == -1) {
2186 		env[4] = NULL;
2187 		goto error;
2188 	}
2189 
2190 	if (opt_key != NULL) {
2191 		rc = asprintf(&env[5], "%s=%s", opt_key,
2192 		    opt_val ? opt_val : "");
2193 		if (rc == -1) {
2194 			env[5] = NULL;
2195 			goto error;
2196 		}
2197 	}
2198 
2199 	return (env);
2200 
2201 error:
2202 	for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2203 		free(env[i]);
2204 
2205 	free(env);
2206 
2207 	return (NULL);
2208 }
2209 
2210 /*
2211  * Free the env[] array that was allocated by zpool_vdev_script_alloc_env().
2212  */
2213 void
2214 zpool_vdev_script_free_env(char **env)
2215 {
2216 	for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2217 		free(env[i]);
2218 
2219 	free(env);
2220 }
2221 
2222 /*
2223  * Prepare a disk by (optionally) running a program before labeling the disk.
2224  * This can be useful for installing disk firmware or doing some pre-flight
2225  * checks on the disk before it becomes part of the pool.  The program run is
2226  * located at ZFSEXECDIR/zfs_prepare_disk
2227  * (E.x: /usr/local/libexec/zfs/zfs_prepare_disk).
2228  *
2229  * Return 0 on success, non-zero on failure.
2230  */
2231 int
2232 zpool_prepare_disk(zpool_handle_t *zhp, nvlist_t *vdev_nv,
2233     const char *prepare_str, char **lines[], int *lines_cnt)
2234 {
2235 	const char *script_path = ZFSEXECDIR "/zfs_prepare_disk";
2236 	const char *pool_name;
2237 	int rc = 0;
2238 
2239 	/* Path to script and a NULL entry */
2240 	char *argv[2] = {(char *)script_path};
2241 	char **env = NULL;
2242 	char *path = NULL, *enc_sysfs_path = NULL;
2243 	char *upath;
2244 	*lines_cnt = 0;
2245 
2246 	if (access(script_path, X_OK) != 0) {
2247 		/* No script, nothing to do */
2248 		return (0);
2249 	}
2250 
2251 	(void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH, &path);
2252 	(void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
2253 	    &enc_sysfs_path);
2254 
2255 	upath = zfs_get_underlying_path(path);
2256 	pool_name = zhp ? zpool_get_name(zhp) : NULL;
2257 
2258 	env = zpool_vdev_script_alloc_env(pool_name, path, upath,
2259 	    enc_sysfs_path, "VDEV_PREPARE", prepare_str);
2260 
2261 	free(upath);
2262 
2263 	if (env == NULL) {
2264 		return (ENOMEM);
2265 	}
2266 
2267 	rc = libzfs_run_process_get_stdout(script_path, argv, env, lines,
2268 	    lines_cnt);
2269 
2270 	zpool_vdev_script_free_env(env);
2271 
2272 	return (rc);
2273 }
2274 
2275 /*
2276  * Optionally run a script and then label a disk.  The script can be used to
2277  * prepare a disk for inclusion into the pool.  For example, it might update
2278  * the disk's firmware or check its health.
2279  *
2280  * The 'name' provided is the short name, stripped of any leading
2281  * /dev path, and is passed to zpool_label_disk. vdev_nv is the nvlist for
2282  * the vdev.  prepare_str is a string that gets passed as the VDEV_PREPARE
2283  * env variable to the script.
2284  *
2285  * The following env vars are passed to the script:
2286  *
2287  * POOL_NAME:		The pool name (blank during zpool create)
2288  * VDEV_PREPARE:	Reason why the disk is being prepared for inclusion:
2289  *			"create", "add", "replace", or "autoreplace"
2290  * VDEV_PATH:		Path to the disk
2291  * VDEV_UPATH:		One of the 'underlying paths' to the disk.  This is
2292  * 			useful for DM devices.
2293  * VDEV_ENC_SYSFS_PATH:	Path to the disk's enclosure sysfs path, if available.
2294  *
2295  * Note, some of these values can be blank.
2296  *
2297  * Return 0 on success, non-zero otherwise.
2298  */
2299 int
2300 zpool_prepare_and_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp,
2301     const char *name, nvlist_t *vdev_nv, const char *prepare_str,
2302     char **lines[], int *lines_cnt)
2303 {
2304 	int rc;
2305 	char vdev_path[MAXPATHLEN];
2306 	(void) snprintf(vdev_path, sizeof (vdev_path), "%s/%s", DISK_ROOT,
2307 	    name);
2308 
2309 	/* zhp will be NULL when creating a pool */
2310 	rc = zpool_prepare_disk(zhp, vdev_nv, prepare_str, lines, lines_cnt);
2311 	if (rc != 0)
2312 		return (rc);
2313 
2314 	rc = zpool_label_disk(hdl, zhp, name);
2315 	return (rc);
2316 }
2317