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