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