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