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