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