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