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 zfs_btree_init();
1090
1091 if (getenv("ZFS_PROP_DEBUG") != NULL) {
1092 hdl->libzfs_prop_debug = B_TRUE;
1093 }
1094 if ((env = getenv("ZFS_SENDRECV_MAX_NVLIST")) != NULL) {
1095 if ((error = zfs_nicestrtonum(hdl, env,
1096 &hdl->libzfs_max_nvlist))) {
1097 errno = error;
1098 (void) close(hdl->libzfs_fd);
1099 free(hdl);
1100 return (NULL);
1101 }
1102 } else {
1103 hdl->libzfs_max_nvlist = (SPA_MAXBLOCKSIZE * 4);
1104 }
1105
1106 /*
1107 * For testing, remove some settable properties and features
1108 */
1109 if (libzfs_envvar_is_set("ZFS_SYSFS_PROP_SUPPORT_TEST")) {
1110 zprop_desc_t *proptbl;
1111
1112 proptbl = zpool_prop_get_table();
1113 proptbl[ZPOOL_PROP_COMMENT].pd_zfs_mod_supported = B_FALSE;
1114
1115 proptbl = zfs_prop_get_table();
1116 proptbl[ZFS_PROP_DNODESIZE].pd_zfs_mod_supported = B_FALSE;
1117
1118 zfeature_info_t *ftbl = spa_feature_table;
1119 ftbl[SPA_FEATURE_LARGE_BLOCKS].fi_zfs_mod_supported = B_FALSE;
1120 }
1121
1122 return (hdl);
1123 }
1124
1125 void
libzfs_fini(libzfs_handle_t * hdl)1126 libzfs_fini(libzfs_handle_t *hdl)
1127 {
1128 (void) close(hdl->libzfs_fd);
1129 zpool_free_handles(hdl);
1130 namespace_clear(hdl);
1131 libzfs_mnttab_fini(hdl);
1132 libzfs_core_fini();
1133 regfree(&hdl->libzfs_urire);
1134 zfs_btree_fini();
1135 fletcher_4_fini();
1136 #if LIBFETCH_DYNAMIC
1137 if (hdl->libfetch != (void *)-1 && hdl->libfetch != NULL)
1138 (void) dlclose(hdl->libfetch);
1139 free(hdl->libfetch_load_error);
1140 #endif
1141 free(hdl);
1142 }
1143
1144 libzfs_handle_t *
zpool_get_handle(zpool_handle_t * zhp)1145 zpool_get_handle(zpool_handle_t *zhp)
1146 {
1147 return (zhp->zpool_hdl);
1148 }
1149
1150 libzfs_handle_t *
zfs_get_handle(zfs_handle_t * zhp)1151 zfs_get_handle(zfs_handle_t *zhp)
1152 {
1153 return (zhp->zfs_hdl);
1154 }
1155
1156 zpool_handle_t *
zfs_get_pool_handle(const zfs_handle_t * zhp)1157 zfs_get_pool_handle(const zfs_handle_t *zhp)
1158 {
1159 return (zhp->zpool_hdl);
1160 }
1161
1162 /*
1163 * Given a name, determine whether or not it's a valid path
1164 * (starts with '/' or "./"). If so, walk the mnttab trying
1165 * to match the device number. If not, treat the path as an
1166 * fs/vol/snap/bkmark name.
1167 */
1168 zfs_handle_t *
zfs_path_to_zhandle(libzfs_handle_t * hdl,const char * path,zfs_type_t argtype)1169 zfs_path_to_zhandle(libzfs_handle_t *hdl, const char *path, zfs_type_t argtype)
1170 {
1171 struct stat64 statbuf;
1172 struct mnttab entry;
1173
1174 if (path[0] != '/' && strncmp(path, "./", strlen("./")) != 0) {
1175 /*
1176 * It's not a valid path, assume it's a name of type 'argtype'.
1177 */
1178 return (zfs_open(hdl, path, argtype));
1179 }
1180
1181 if (getextmntent(path, &entry, &statbuf) != 0)
1182 return (NULL);
1183
1184 if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0) {
1185 (void) fprintf(stderr, gettext("'%s': not a ZFS filesystem\n"),
1186 path);
1187 return (NULL);
1188 }
1189
1190 return (zfs_open(hdl, entry.mnt_special, ZFS_TYPE_FILESYSTEM));
1191 }
1192
1193 /*
1194 * Initialize the zc_nvlist_dst member to prepare for receiving an nvlist from
1195 * an ioctl().
1196 */
1197 void
zcmd_alloc_dst_nvlist(libzfs_handle_t * hdl,zfs_cmd_t * zc,size_t len)1198 zcmd_alloc_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, size_t len)
1199 {
1200 if (len == 0)
1201 len = 256 * 1024;
1202 zc->zc_nvlist_dst_size = len;
1203 zc->zc_nvlist_dst =
1204 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1205 }
1206
1207 /*
1208 * Called when an ioctl() which returns an nvlist fails with ENOMEM. This will
1209 * expand the nvlist to the size specified in 'zc_nvlist_dst_size', which was
1210 * filled in by the kernel to indicate the actual required size.
1211 */
1212 void
zcmd_expand_dst_nvlist(libzfs_handle_t * hdl,zfs_cmd_t * zc)1213 zcmd_expand_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc)
1214 {
1215 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1216 zc->zc_nvlist_dst =
1217 (uint64_t)(uintptr_t)zfs_alloc(hdl, zc->zc_nvlist_dst_size);
1218 }
1219
1220 /*
1221 * Called to free the src and dst nvlists stored in the command structure.
1222 */
1223 void
zcmd_free_nvlists(zfs_cmd_t * zc)1224 zcmd_free_nvlists(zfs_cmd_t *zc)
1225 {
1226 free((void *)(uintptr_t)zc->zc_nvlist_conf);
1227 free((void *)(uintptr_t)zc->zc_nvlist_src);
1228 free((void *)(uintptr_t)zc->zc_nvlist_dst);
1229 zc->zc_nvlist_conf = 0;
1230 zc->zc_nvlist_src = 0;
1231 zc->zc_nvlist_dst = 0;
1232 }
1233
1234 static void
zcmd_write_nvlist_com(libzfs_handle_t * hdl,uint64_t * outnv,uint64_t * outlen,nvlist_t * nvl)1235 zcmd_write_nvlist_com(libzfs_handle_t *hdl, uint64_t *outnv, uint64_t *outlen,
1236 nvlist_t *nvl)
1237 {
1238 char *packed;
1239
1240 size_t len = fnvlist_size(nvl);
1241 packed = zfs_alloc(hdl, len);
1242
1243 verify(nvlist_pack(nvl, &packed, &len, NV_ENCODE_NATIVE, 0) == 0);
1244
1245 *outnv = (uint64_t)(uintptr_t)packed;
1246 *outlen = len;
1247 }
1248
1249 void
zcmd_write_conf_nvlist(libzfs_handle_t * hdl,zfs_cmd_t * zc,nvlist_t * nvl)1250 zcmd_write_conf_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1251 {
1252 zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_conf,
1253 &zc->zc_nvlist_conf_size, nvl);
1254 }
1255
1256 void
zcmd_write_src_nvlist(libzfs_handle_t * hdl,zfs_cmd_t * zc,nvlist_t * nvl)1257 zcmd_write_src_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t *nvl)
1258 {
1259 zcmd_write_nvlist_com(hdl, &zc->zc_nvlist_src,
1260 &zc->zc_nvlist_src_size, nvl);
1261 }
1262
1263 /*
1264 * Unpacks an nvlist from the ZFS ioctl command structure.
1265 */
1266 int
zcmd_read_dst_nvlist(libzfs_handle_t * hdl,zfs_cmd_t * zc,nvlist_t ** nvlp)1267 zcmd_read_dst_nvlist(libzfs_handle_t *hdl, zfs_cmd_t *zc, nvlist_t **nvlp)
1268 {
1269 if (nvlist_unpack((void *)(uintptr_t)zc->zc_nvlist_dst,
1270 zc->zc_nvlist_dst_size, nvlp, 0) != 0)
1271 return (no_memory(hdl));
1272
1273 return (0);
1274 }
1275
1276 /*
1277 * ================================================================
1278 * API shared by zfs and zpool property management
1279 * ================================================================
1280 */
1281
1282 void
zcmd_print_json(nvlist_t * nvl)1283 zcmd_print_json(nvlist_t *nvl)
1284 {
1285 nvlist_print_json(stdout, nvl);
1286 (void) putchar('\n');
1287 nvlist_free(nvl);
1288 }
1289
1290 static void
zprop_print_headers(zprop_get_cbdata_t * cbp,zfs_type_t type)1291 zprop_print_headers(zprop_get_cbdata_t *cbp, zfs_type_t type)
1292 {
1293 zprop_list_t *pl;
1294 int i;
1295 char *title;
1296 size_t len;
1297
1298 cbp->cb_first = B_FALSE;
1299 if (cbp->cb_scripted)
1300 return;
1301
1302 /*
1303 * Start with the length of the column headers.
1304 */
1305 cbp->cb_colwidths[GET_COL_NAME] = strlen(dgettext(TEXT_DOMAIN, "NAME"));
1306 cbp->cb_colwidths[GET_COL_PROPERTY] = strlen(dgettext(TEXT_DOMAIN,
1307 "PROPERTY"));
1308 cbp->cb_colwidths[GET_COL_VALUE] = strlen(dgettext(TEXT_DOMAIN,
1309 "VALUE"));
1310 cbp->cb_colwidths[GET_COL_RECVD] = strlen(dgettext(TEXT_DOMAIN,
1311 "RECEIVED"));
1312 cbp->cb_colwidths[GET_COL_SOURCE] = strlen(dgettext(TEXT_DOMAIN,
1313 "SOURCE"));
1314
1315 /* first property is always NAME */
1316 assert(cbp->cb_proplist->pl_prop ==
1317 ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1318 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME)));
1319
1320 /*
1321 * Go through and calculate the widths for each column. For the
1322 * 'source' column, we kludge it up by taking the worst-case scenario of
1323 * inheriting from the longest name. This is acceptable because in the
1324 * majority of cases 'SOURCE' is the last column displayed, and we don't
1325 * use the width anyway. Note that the 'VALUE' column can be oversized,
1326 * if the name of the property is much longer than any values we find.
1327 */
1328 for (pl = cbp->cb_proplist; pl != NULL; pl = pl->pl_next) {
1329 /*
1330 * 'PROPERTY' column
1331 */
1332 if (pl->pl_prop != ZPROP_USERPROP) {
1333 const char *propname = (type == ZFS_TYPE_POOL) ?
1334 zpool_prop_to_name(pl->pl_prop) :
1335 ((type == ZFS_TYPE_VDEV) ?
1336 vdev_prop_to_name(pl->pl_prop) :
1337 zfs_prop_to_name(pl->pl_prop));
1338
1339 assert(propname != NULL);
1340 len = strlen(propname);
1341 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1342 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1343 } else {
1344 assert(pl->pl_user_prop != NULL);
1345 len = strlen(pl->pl_user_prop);
1346 if (len > cbp->cb_colwidths[GET_COL_PROPERTY])
1347 cbp->cb_colwidths[GET_COL_PROPERTY] = len;
1348 }
1349
1350 /*
1351 * 'VALUE' column. The first property is always the 'name'
1352 * property that was tacked on either by /sbin/zfs's
1353 * zfs_do_get() or when calling zprop_expand_list(), so we
1354 * ignore its width. If the user specified the name property
1355 * to display, then it will be later in the list in any case.
1356 */
1357 if (pl != cbp->cb_proplist &&
1358 pl->pl_width > cbp->cb_colwidths[GET_COL_VALUE])
1359 cbp->cb_colwidths[GET_COL_VALUE] = pl->pl_width;
1360
1361 /* 'RECEIVED' column. */
1362 if (pl != cbp->cb_proplist &&
1363 pl->pl_recvd_width > cbp->cb_colwidths[GET_COL_RECVD])
1364 cbp->cb_colwidths[GET_COL_RECVD] = pl->pl_recvd_width;
1365
1366 /*
1367 * 'NAME' and 'SOURCE' columns
1368 */
1369 if (pl->pl_prop == ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
1370 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME :
1371 ZFS_PROP_NAME)) && pl->pl_width >
1372 cbp->cb_colwidths[GET_COL_NAME]) {
1373 cbp->cb_colwidths[GET_COL_NAME] = pl->pl_width;
1374 cbp->cb_colwidths[GET_COL_SOURCE] = pl->pl_width +
1375 strlen(dgettext(TEXT_DOMAIN, "inherited from"));
1376 }
1377 }
1378
1379 /*
1380 * Now go through and print the headers.
1381 */
1382 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1383 switch (cbp->cb_columns[i]) {
1384 case GET_COL_NAME:
1385 title = dgettext(TEXT_DOMAIN, "NAME");
1386 break;
1387 case GET_COL_PROPERTY:
1388 title = dgettext(TEXT_DOMAIN, "PROPERTY");
1389 break;
1390 case GET_COL_VALUE:
1391 title = dgettext(TEXT_DOMAIN, "VALUE");
1392 break;
1393 case GET_COL_RECVD:
1394 title = dgettext(TEXT_DOMAIN, "RECEIVED");
1395 break;
1396 case GET_COL_SOURCE:
1397 title = dgettext(TEXT_DOMAIN, "SOURCE");
1398 break;
1399 default:
1400 title = NULL;
1401 }
1402
1403 if (title != NULL) {
1404 if (i == (ZFS_GET_NCOLS - 1) ||
1405 cbp->cb_columns[i + 1] == GET_COL_NONE)
1406 (void) printf("%s", title);
1407 else
1408 (void) printf("%-*s ",
1409 cbp->cb_colwidths[cbp->cb_columns[i]],
1410 title);
1411 }
1412 }
1413 (void) printf("\n");
1414 }
1415
1416 /*
1417 * Add property value and source to provided nvlist, according to
1418 * settings in cb structure. Later to be printed in JSON format.
1419 */
1420 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)1421 zprop_nvlist_one_property(const char *propname,
1422 const char *value, zprop_source_t sourcetype, const char *source,
1423 const char *recvd_value, nvlist_t *nvl, boolean_t as_int)
1424 {
1425 int ret = 0;
1426 nvlist_t *src_nv, *prop;
1427 boolean_t all_numeric = strspn(value, STR_NUMS) == strlen(value);
1428 src_nv = prop = NULL;
1429
1430 if ((nvlist_alloc(&prop, NV_UNIQUE_NAME, 0) != 0) ||
1431 (nvlist_alloc(&src_nv, NV_UNIQUE_NAME, 0) != 0)) {
1432 ret = -1;
1433 goto err;
1434 }
1435
1436 if (as_int && all_numeric) {
1437 uint64_t val;
1438 sscanf(value, "%lld", (u_longlong_t *)&val);
1439 if (nvlist_add_uint64(prop, "value", val) != 0) {
1440 ret = -1;
1441 goto err;
1442 }
1443 } else {
1444 if (nvlist_add_string(prop, "value", value) != 0) {
1445 ret = -1;
1446 goto err;
1447 }
1448 }
1449
1450 switch (sourcetype) {
1451 case ZPROP_SRC_NONE:
1452 if (nvlist_add_string(src_nv, "type", "NONE") != 0 ||
1453 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1454 ret = -1;
1455 goto err;
1456 }
1457 break;
1458 case ZPROP_SRC_DEFAULT:
1459 if (nvlist_add_string(src_nv, "type", "DEFAULT") != 0 ||
1460 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1461 ret = -1;
1462 goto err;
1463 }
1464 break;
1465 case ZPROP_SRC_LOCAL:
1466 if (nvlist_add_string(src_nv, "type", "LOCAL") != 0 ||
1467 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1468 ret = -1;
1469 goto err;
1470 }
1471 break;
1472 case ZPROP_SRC_TEMPORARY:
1473 if (nvlist_add_string(src_nv, "type", "TEMPORARY") != 0 ||
1474 (nvlist_add_string(src_nv, "data", "-") != 0)) {
1475 ret = -1;
1476 goto err;
1477 }
1478 break;
1479 case ZPROP_SRC_INHERITED:
1480 if (nvlist_add_string(src_nv, "type", "INHERITED") != 0 ||
1481 (nvlist_add_string(src_nv, "data", source) != 0)) {
1482 ret = -1;
1483 goto err;
1484 }
1485 break;
1486 case ZPROP_SRC_RECEIVED:
1487 if (nvlist_add_string(src_nv, "type", "RECEIVED") != 0 ||
1488 (nvlist_add_string(src_nv, "data",
1489 (recvd_value == NULL ? "-" : recvd_value)) != 0)) {
1490 ret = -1;
1491 goto err;
1492 }
1493 break;
1494 default:
1495 assert(!"unhandled zprop_source_t");
1496 if (nvlist_add_string(src_nv, "type",
1497 "unhandled zprop_source_t") != 0) {
1498 ret = -1;
1499 goto err;
1500 }
1501 }
1502 if ((nvlist_add_nvlist(prop, "source", src_nv) != 0) ||
1503 (nvlist_add_nvlist(nvl, propname, prop)) != 0) {
1504 ret = -1;
1505 goto err;
1506 }
1507 err:
1508 nvlist_free(src_nv);
1509 nvlist_free(prop);
1510 return (ret);
1511 }
1512
1513 /*
1514 * Display a single line of output, according to the settings in the callback
1515 * structure.
1516 */
1517 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)1518 zprop_print_one_property(const char *name, zprop_get_cbdata_t *cbp,
1519 const char *propname, const char *value, zprop_source_t sourcetype,
1520 const char *source, const char *recvd_value)
1521 {
1522 int i;
1523 const char *str = NULL;
1524 char buf[128];
1525
1526 /*
1527 * Ignore those source types that the user has chosen to ignore.
1528 */
1529 if ((sourcetype & cbp->cb_sources) == 0)
1530 return;
1531
1532 if (cbp->cb_first)
1533 zprop_print_headers(cbp, cbp->cb_type);
1534
1535 for (i = 0; i < ZFS_GET_NCOLS; i++) {
1536 switch (cbp->cb_columns[i]) {
1537 case GET_COL_NAME:
1538 str = name;
1539 break;
1540
1541 case GET_COL_PROPERTY:
1542 str = propname;
1543 break;
1544
1545 case GET_COL_VALUE:
1546 str = value;
1547 break;
1548
1549 case GET_COL_SOURCE:
1550 switch (sourcetype) {
1551 case ZPROP_SRC_NONE:
1552 str = "-";
1553 break;
1554
1555 case ZPROP_SRC_DEFAULT:
1556 str = "default";
1557 break;
1558
1559 case ZPROP_SRC_LOCAL:
1560 str = "local";
1561 break;
1562
1563 case ZPROP_SRC_TEMPORARY:
1564 str = "temporary";
1565 break;
1566
1567 case ZPROP_SRC_INHERITED:
1568 (void) snprintf(buf, sizeof (buf),
1569 "inherited from %s", source);
1570 str = buf;
1571 break;
1572 case ZPROP_SRC_RECEIVED:
1573 str = "received";
1574 break;
1575
1576 default:
1577 str = NULL;
1578 assert(!"unhandled zprop_source_t");
1579 }
1580 break;
1581
1582 case GET_COL_RECVD:
1583 str = (recvd_value == NULL ? "-" : recvd_value);
1584 break;
1585
1586 default:
1587 continue;
1588 }
1589
1590 if (i == (ZFS_GET_NCOLS - 1) ||
1591 cbp->cb_columns[i + 1] == GET_COL_NONE)
1592 (void) printf("%s", str);
1593 else if (cbp->cb_scripted)
1594 (void) printf("%s\t", str);
1595 else
1596 (void) printf("%-*s ",
1597 cbp->cb_colwidths[cbp->cb_columns[i]],
1598 str);
1599 }
1600
1601 (void) printf("\n");
1602 }
1603
1604 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)1605 zprop_collect_property(const char *name, zprop_get_cbdata_t *cbp,
1606 const char *propname, const char *value, zprop_source_t sourcetype,
1607 const char *source, const char *recvd_value, nvlist_t *nvl)
1608 {
1609 if (cbp->cb_json) {
1610 if ((sourcetype & cbp->cb_sources) == 0)
1611 return (0);
1612 else {
1613 return (zprop_nvlist_one_property(propname, value,
1614 sourcetype, source, recvd_value, nvl,
1615 cbp->cb_json_as_int));
1616 }
1617 } else {
1618 zprop_print_one_property(name, cbp,
1619 propname, value, sourcetype, source, recvd_value);
1620 return (0);
1621 }
1622 }
1623
1624 /*
1625 * Given a numeric suffix, convert the value into a number of bits that the
1626 * resulting value must be shifted.
1627 */
1628 static int
str2shift(libzfs_handle_t * hdl,const char * buf)1629 str2shift(libzfs_handle_t *hdl, const char *buf)
1630 {
1631 const char *ends = "BKMGTPEZ";
1632 int i, len;
1633
1634 if (buf[0] == '\0')
1635 return (0);
1636
1637 len = strlen(ends);
1638 for (i = 0; i < len; i++) {
1639 if (toupper(buf[0]) == ends[i])
1640 break;
1641 }
1642 if (i == len) {
1643 if (hdl)
1644 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1645 "invalid numeric suffix '%s'"), buf);
1646 return (-1);
1647 }
1648
1649 /*
1650 * Allow 'G' = 'GB' = 'GiB', case-insensitively.
1651 * However, 'BB' and 'BiB' are disallowed.
1652 */
1653 if (buf[1] == '\0' ||
1654 (toupper(buf[0]) != 'B' &&
1655 ((toupper(buf[1]) == 'B' && buf[2] == '\0') ||
1656 (toupper(buf[1]) == 'I' && toupper(buf[2]) == 'B' &&
1657 buf[3] == '\0'))))
1658 return (10 * i);
1659
1660 if (hdl)
1661 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1662 "invalid numeric suffix '%s'"), buf);
1663 return (-1);
1664 }
1665
1666 /*
1667 * Convert a string of the form '100G' into a real number. Used when setting
1668 * properties or creating a volume. 'buf' is used to place an extended error
1669 * message for the caller to use.
1670 */
1671 int
zfs_nicestrtonum(libzfs_handle_t * hdl,const char * value,uint64_t * num)1672 zfs_nicestrtonum(libzfs_handle_t *hdl, const char *value, uint64_t *num)
1673 {
1674 char *end;
1675 int shift;
1676
1677 *num = 0;
1678
1679 /* Check to see if this looks like a number. */
1680 if ((value[0] < '0' || value[0] > '9') && value[0] != '.') {
1681 if (hdl)
1682 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1683 "bad numeric value '%s'"), value);
1684 return (-1);
1685 }
1686
1687 /* Rely on strtoull() to process the numeric portion. */
1688 errno = 0;
1689 *num = strtoull(value, &end, 10);
1690
1691 /*
1692 * Check for ERANGE, which indicates that the value is too large to fit
1693 * in a 64-bit value.
1694 */
1695 if (errno == ERANGE) {
1696 if (hdl)
1697 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1698 "numeric value is too large"));
1699 return (-1);
1700 }
1701
1702 /*
1703 * If we have a decimal value, then do the computation with floating
1704 * point arithmetic. Otherwise, use standard arithmetic.
1705 */
1706 if (*end == '.') {
1707 double fval = strtod(value, &end);
1708
1709 if ((shift = str2shift(hdl, end)) == -1)
1710 return (-1);
1711
1712 fval *= pow(2, shift);
1713
1714 /*
1715 * UINT64_MAX is not exactly representable as a double.
1716 * The closest representation is UINT64_MAX + 1, so we
1717 * use a >= comparison instead of > for the bounds check.
1718 */
1719 if (fval >= (double)UINT64_MAX) {
1720 if (hdl)
1721 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1722 "numeric value is too large"));
1723 return (-1);
1724 }
1725
1726 *num = (uint64_t)fval;
1727 } else {
1728 if ((shift = str2shift(hdl, end)) == -1)
1729 return (-1);
1730
1731 /* Check for overflow */
1732 if (shift >= 64 || (*num << shift) >> shift != *num) {
1733 if (hdl)
1734 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1735 "numeric value is too large"));
1736 return (-1);
1737 }
1738
1739 *num <<= shift;
1740 }
1741
1742 return (0);
1743 }
1744
1745 /*
1746 * Given a propname=value nvpair to set, parse any numeric properties
1747 * (index, boolean, etc) if they are specified as strings and add the
1748 * resulting nvpair to the returned nvlist.
1749 *
1750 * At the DSL layer, all properties are either 64-bit numbers or strings.
1751 * We want the user to be able to ignore this fact and specify properties
1752 * as native values (numbers, for example) or as strings (to simplify
1753 * command line utilities). This also handles converting index types
1754 * (compression, checksum, etc) from strings to their on-disk index.
1755 */
1756 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)1757 zprop_parse_value(libzfs_handle_t *hdl, nvpair_t *elem, int prop,
1758 zfs_type_t type, nvlist_t *ret, const char **svalp, uint64_t *ivalp,
1759 const char *errbuf)
1760 {
1761 data_type_t datatype = nvpair_type(elem);
1762 zprop_type_t proptype;
1763 const char *propname;
1764 const char *value;
1765 boolean_t isnone = B_FALSE;
1766 boolean_t isauto = B_FALSE;
1767 int err = 0;
1768
1769 if (type == ZFS_TYPE_POOL) {
1770 proptype = zpool_prop_get_type(prop);
1771 propname = zpool_prop_to_name(prop);
1772 } else if (type == ZFS_TYPE_VDEV) {
1773 proptype = vdev_prop_get_type(prop);
1774 propname = vdev_prop_to_name(prop);
1775 } else {
1776 proptype = zfs_prop_get_type(prop);
1777 propname = zfs_prop_to_name(prop);
1778 }
1779
1780 /*
1781 * Convert any properties to the internal DSL value types.
1782 */
1783 *svalp = NULL;
1784 *ivalp = 0;
1785
1786 switch (proptype) {
1787 case PROP_TYPE_STRING:
1788 if (datatype != DATA_TYPE_STRING) {
1789 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1790 "'%s' must be a string"), nvpair_name(elem));
1791 goto error;
1792 }
1793 err = nvpair_value_string(elem, svalp);
1794 if (err != 0) {
1795 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1796 "'%s' is invalid"), nvpair_name(elem));
1797 goto error;
1798 }
1799 if (strlen(*svalp) >= ZFS_MAXPROPLEN) {
1800 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1801 "'%s' is too long"), nvpair_name(elem));
1802 goto error;
1803 }
1804 break;
1805
1806 case PROP_TYPE_NUMBER:
1807 if (datatype == DATA_TYPE_STRING) {
1808 (void) nvpair_value_string(elem, &value);
1809 if (strcmp(value, "none") == 0) {
1810 isnone = B_TRUE;
1811 } else if (strcmp(value, "auto") == 0) {
1812 isauto = B_TRUE;
1813 } else if (zfs_nicestrtonum(hdl, value, ivalp) != 0) {
1814 goto error;
1815 }
1816 } else if (datatype == DATA_TYPE_UINT64) {
1817 (void) nvpair_value_uint64(elem, ivalp);
1818 } else {
1819 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1820 "'%s' must be a number"), nvpair_name(elem));
1821 goto error;
1822 }
1823
1824 /*
1825 * Quota special: force 'none' and don't allow 0.
1826 */
1827 if ((type & ZFS_TYPE_DATASET) && *ivalp == 0 && !isnone &&
1828 (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_REFQUOTA)) {
1829 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1830 "use 'none' to disable quota/refquota"));
1831 goto error;
1832 }
1833 /*
1834 * Pool dedup table quota; force use of 'none' instead of 0
1835 */
1836 if ((type & ZFS_TYPE_POOL) && *ivalp == 0 &&
1837 (!isnone && !isauto) &&
1838 prop == ZPOOL_PROP_DEDUP_TABLE_QUOTA) {
1839 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1840 "use 'none' to disable ddt table quota"));
1841 goto error;
1842 }
1843
1844 /*
1845 * Special handling for "*_limit=none". In this case it's not
1846 * 0 but UINT64_MAX.
1847 */
1848 if ((type & ZFS_TYPE_DATASET) && isnone &&
1849 (prop == ZFS_PROP_FILESYSTEM_LIMIT ||
1850 prop == ZFS_PROP_SNAPSHOT_LIMIT)) {
1851 *ivalp = UINT64_MAX;
1852 }
1853
1854 /*
1855 * Special handling for "checksum_*=none". In this case it's not
1856 * 0 but UINT64_MAX.
1857 */
1858 if ((type & ZFS_TYPE_VDEV) && isnone &&
1859 (prop == VDEV_PROP_CHECKSUM_N ||
1860 prop == VDEV_PROP_CHECKSUM_T ||
1861 prop == VDEV_PROP_IO_N ||
1862 prop == VDEV_PROP_IO_T ||
1863 prop == VDEV_PROP_SLOW_IO_N ||
1864 prop == VDEV_PROP_SLOW_IO_T)) {
1865 *ivalp = UINT64_MAX;
1866 }
1867
1868 /*
1869 * Special handling for setting 'refreservation' to 'auto'. Use
1870 * UINT64_MAX to tell the caller to use zfs_fix_auto_resv().
1871 * 'auto' is only allowed on volumes.
1872 */
1873 if (isauto) {
1874 switch (prop) {
1875 case ZFS_PROP_REFRESERVATION:
1876 if ((type & ZFS_TYPE_VOLUME) == 0) {
1877 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1878 "'%s=auto' only allowed on "
1879 "volumes"), nvpair_name(elem));
1880 goto error;
1881 }
1882 *ivalp = UINT64_MAX;
1883 break;
1884 case ZPOOL_PROP_DEDUP_TABLE_QUOTA:
1885 ASSERT(type & ZFS_TYPE_POOL);
1886 *ivalp = UINT64_MAX;
1887 break;
1888 default:
1889 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1890 "'auto' is invalid value for '%s'"),
1891 nvpair_name(elem));
1892 goto error;
1893 }
1894 }
1895
1896 break;
1897
1898 case PROP_TYPE_INDEX:
1899 if (datatype != DATA_TYPE_STRING) {
1900 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1901 "'%s' must be a string"), nvpair_name(elem));
1902 goto error;
1903 }
1904
1905 (void) nvpair_value_string(elem, &value);
1906
1907 if (zprop_string_to_index(prop, value, ivalp, type) != 0) {
1908 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1909 "'%s' must be one of '%s'"), propname,
1910 zprop_values(prop, type));
1911 goto error;
1912 }
1913 break;
1914
1915 default:
1916 abort();
1917 }
1918
1919 /*
1920 * Add the result to our return set of properties.
1921 */
1922 if (*svalp != NULL) {
1923 if (nvlist_add_string(ret, propname, *svalp) != 0) {
1924 (void) no_memory(hdl);
1925 return (-1);
1926 }
1927 } else {
1928 if (nvlist_add_uint64(ret, propname, *ivalp) != 0) {
1929 (void) no_memory(hdl);
1930 return (-1);
1931 }
1932 }
1933
1934 return (0);
1935 error:
1936 (void) zfs_error(hdl, EZFS_BADPROP, errbuf);
1937 return (-1);
1938 }
1939
1940 static int
addlist(libzfs_handle_t * hdl,const char * propname,zprop_list_t ** listp,zfs_type_t type)1941 addlist(libzfs_handle_t *hdl, const char *propname, zprop_list_t **listp,
1942 zfs_type_t type)
1943 {
1944 int prop = zprop_name_to_prop(propname, type);
1945 if (prop != ZPROP_INVAL && !zprop_valid_for_type(prop, type, B_FALSE))
1946 prop = ZPROP_INVAL;
1947
1948 /*
1949 * Return failure if no property table entry was found and this isn't
1950 * a user-defined property.
1951 */
1952 if (prop == ZPROP_USERPROP && ((type == ZFS_TYPE_POOL &&
1953 !zfs_prop_user(propname) &&
1954 !zpool_prop_feature(propname) &&
1955 !zpool_prop_unsupported(propname)) ||
1956 ((type == ZFS_TYPE_DATASET) && !zfs_prop_user(propname) &&
1957 !zfs_prop_userquota(propname) && !zfs_prop_written(propname)) ||
1958 ((type == ZFS_TYPE_VDEV) && !vdev_prop_user(propname)))) {
1959 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1960 "invalid property '%s'"), propname);
1961 return (zfs_error(hdl, EZFS_BADPROP,
1962 dgettext(TEXT_DOMAIN, "bad property list")));
1963 }
1964
1965 zprop_list_t *entry = zfs_alloc(hdl, sizeof (*entry));
1966
1967 entry->pl_prop = prop;
1968 if (prop == ZPROP_USERPROP) {
1969 entry->pl_user_prop = zfs_strdup(hdl, propname);
1970 entry->pl_width = strlen(propname);
1971 } else {
1972 entry->pl_width = zprop_width(prop, &entry->pl_fixed,
1973 type);
1974 }
1975
1976 *listp = entry;
1977
1978 return (0);
1979 }
1980
1981 /*
1982 * Given a comma-separated list of properties, construct a property list
1983 * containing both user-defined and native properties. This function will
1984 * return a NULL list if 'all' is specified, which can later be expanded
1985 * by zprop_expand_list().
1986 */
1987 int
zprop_get_list(libzfs_handle_t * hdl,char * props,zprop_list_t ** listp,zfs_type_t type)1988 zprop_get_list(libzfs_handle_t *hdl, char *props, zprop_list_t **listp,
1989 zfs_type_t type)
1990 {
1991 *listp = NULL;
1992
1993 /*
1994 * If 'all' is specified, return a NULL list.
1995 */
1996 if (strcmp(props, "all") == 0)
1997 return (0);
1998
1999 /*
2000 * If no props were specified, return an error.
2001 */
2002 if (props[0] == '\0') {
2003 zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2004 "no properties specified"));
2005 return (zfs_error(hdl, EZFS_BADPROP, dgettext(TEXT_DOMAIN,
2006 "bad property list")));
2007 }
2008
2009 for (char *p; (p = strsep(&props, ",")); )
2010 if (strcmp(p, "space") == 0) {
2011 static const char *const spaceprops[] = {
2012 "name", "avail", "used", "usedbysnapshots",
2013 "usedbydataset", "usedbyrefreservation",
2014 "usedbychildren"
2015 };
2016
2017 for (int i = 0; i < ARRAY_SIZE(spaceprops); i++) {
2018 if (addlist(hdl, spaceprops[i], listp, type))
2019 return (-1);
2020 listp = &(*listp)->pl_next;
2021 }
2022 } else {
2023 if (addlist(hdl, p, listp, type))
2024 return (-1);
2025 listp = &(*listp)->pl_next;
2026 }
2027
2028 return (0);
2029 }
2030
2031 void
zprop_free_list(zprop_list_t * pl)2032 zprop_free_list(zprop_list_t *pl)
2033 {
2034 zprop_list_t *next;
2035
2036 while (pl != NULL) {
2037 next = pl->pl_next;
2038 free(pl->pl_user_prop);
2039 free(pl);
2040 pl = next;
2041 }
2042 }
2043
2044 typedef struct expand_data {
2045 zprop_list_t **last;
2046 libzfs_handle_t *hdl;
2047 zfs_type_t type;
2048 } expand_data_t;
2049
2050 static int
zprop_expand_list_cb(int prop,void * cb)2051 zprop_expand_list_cb(int prop, void *cb)
2052 {
2053 zprop_list_t *entry;
2054 expand_data_t *edp = cb;
2055
2056 entry = zfs_alloc(edp->hdl, sizeof (zprop_list_t));
2057
2058 entry->pl_prop = prop;
2059 entry->pl_width = zprop_width(prop, &entry->pl_fixed, edp->type);
2060 entry->pl_all = B_TRUE;
2061
2062 *(edp->last) = entry;
2063 edp->last = &entry->pl_next;
2064
2065 return (ZPROP_CONT);
2066 }
2067
2068 int
zprop_expand_list(libzfs_handle_t * hdl,zprop_list_t ** plp,zfs_type_t type)2069 zprop_expand_list(libzfs_handle_t *hdl, zprop_list_t **plp, zfs_type_t type)
2070 {
2071 zprop_list_t *entry;
2072 zprop_list_t **last;
2073 expand_data_t exp;
2074
2075 if (*plp == NULL) {
2076 /*
2077 * If this is the very first time we've been called for an 'all'
2078 * specification, expand the list to include all native
2079 * properties.
2080 */
2081 last = plp;
2082
2083 exp.last = last;
2084 exp.hdl = hdl;
2085 exp.type = type;
2086
2087 if (zprop_iter_common(zprop_expand_list_cb, &exp, B_FALSE,
2088 B_FALSE, type) == ZPROP_INVAL)
2089 return (-1);
2090
2091 /*
2092 * Add 'name' to the beginning of the list, which is handled
2093 * specially.
2094 */
2095 entry = zfs_alloc(hdl, sizeof (zprop_list_t));
2096 entry->pl_prop = ((type == ZFS_TYPE_POOL) ? ZPOOL_PROP_NAME :
2097 ((type == ZFS_TYPE_VDEV) ? VDEV_PROP_NAME : ZFS_PROP_NAME));
2098 entry->pl_width = zprop_width(entry->pl_prop,
2099 &entry->pl_fixed, type);
2100 entry->pl_all = B_TRUE;
2101 entry->pl_next = *plp;
2102 *plp = entry;
2103 }
2104 return (0);
2105 }
2106
2107 int
zprop_iter(zprop_func func,void * cb,boolean_t show_all,boolean_t ordered,zfs_type_t type)2108 zprop_iter(zprop_func func, void *cb, boolean_t show_all, boolean_t ordered,
2109 zfs_type_t type)
2110 {
2111 return (zprop_iter_common(func, cb, show_all, ordered, type));
2112 }
2113
2114 const char *
zfs_version_userland(void)2115 zfs_version_userland(void)
2116 {
2117 return (ZFS_META_ALIAS);
2118 }
2119
2120 /*
2121 * Prints both zfs userland and kernel versions
2122 * Returns 0 on success, and -1 on error
2123 */
2124 int
zfs_version_print(void)2125 zfs_version_print(void)
2126 {
2127 (void) puts(ZFS_META_ALIAS);
2128
2129 char *kver = zfs_version_kernel();
2130 if (kver == NULL) {
2131 fprintf(stderr, "zfs_version_kernel() failed: %s\n",
2132 zfs_strerror(errno));
2133 return (-1);
2134 }
2135
2136 (void) printf("zfs-kmod-%s\n", kver);
2137 free(kver);
2138 return (0);
2139 }
2140
2141 /*
2142 * Returns an nvlist with both zfs userland and kernel versions.
2143 * Returns NULL on error.
2144 */
2145 nvlist_t *
zfs_version_nvlist(void)2146 zfs_version_nvlist(void)
2147 {
2148 nvlist_t *nvl;
2149 char kmod_ver[64];
2150 if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
2151 return (NULL);
2152 if (nvlist_add_string(nvl, "userland", ZFS_META_ALIAS) != 0)
2153 goto err;
2154 char *kver = zfs_version_kernel();
2155 if (kver == NULL) {
2156 fprintf(stderr, "zfs_version_kernel() failed: %s\n",
2157 zfs_strerror(errno));
2158 goto err;
2159 }
2160 (void) snprintf(kmod_ver, 64, "zfs-kmod-%s", kver);
2161 if (nvlist_add_string(nvl, "kernel", kmod_ver) != 0)
2162 goto err;
2163 return (nvl);
2164 err:
2165 nvlist_free(nvl);
2166 return (NULL);
2167 }
2168
2169 /*
2170 * Return 1 if the user requested ANSI color output, and our terminal supports
2171 * it. Return 0 for no color.
2172 */
2173 int
use_color(void)2174 use_color(void)
2175 {
2176 static int use_color = -1;
2177 char *term;
2178
2179 /*
2180 * Optimization:
2181 *
2182 * For each zpool invocation, we do a single check to see if we should
2183 * be using color or not, and cache that value for the lifetime of the
2184 * the zpool command. That makes it cheap to call use_color() when
2185 * we're printing with color. We assume that the settings are not going
2186 * to change during the invocation of a zpool command (the user isn't
2187 * going to change the ZFS_COLOR value while zpool is running, for
2188 * example).
2189 */
2190 if (use_color != -1) {
2191 /*
2192 * We've already figured out if we should be using color or
2193 * not. Return the cached value.
2194 */
2195 return (use_color);
2196 }
2197
2198 term = getenv("TERM");
2199 /*
2200 * The user sets the ZFS_COLOR env var set to enable zpool ANSI color
2201 * output. However if NO_COLOR is set (https://no-color.org/) then
2202 * don't use it. Also, don't use color if terminal doesn't support
2203 * it.
2204 */
2205 if (libzfs_envvar_is_set("ZFS_COLOR") &&
2206 !libzfs_envvar_is_set("NO_COLOR") &&
2207 isatty(STDOUT_FILENO) && term && strcmp("dumb", term) != 0 &&
2208 strcmp("unknown", term) != 0) {
2209 /* Color supported */
2210 use_color = 1;
2211 } else {
2212 use_color = 0;
2213 }
2214
2215 return (use_color);
2216 }
2217
2218 /*
2219 * The functions color_start() and color_end() are used for when you want
2220 * to colorize a block of text.
2221 *
2222 * For example:
2223 * color_start(ANSI_RED)
2224 * printf("hello");
2225 * printf("world");
2226 * color_end();
2227 */
2228 void
color_start(const char * color)2229 color_start(const char *color)
2230 {
2231 if (color && use_color()) {
2232 fputs(color, stdout);
2233 fflush(stdout);
2234 }
2235 }
2236
2237 void
color_end(void)2238 color_end(void)
2239 {
2240 if (use_color()) {
2241 fputs(ANSI_RESET, stdout);
2242 fflush(stdout);
2243 }
2244
2245 }
2246
2247 /*
2248 * printf() with a color. If color is NULL, then do a normal printf.
2249 */
2250 int
printf_color(const char * color,const char * format,...)2251 printf_color(const char *color, const char *format, ...)
2252 {
2253 va_list aptr;
2254 int rc;
2255
2256 if (color)
2257 color_start(color);
2258
2259 va_start(aptr, format);
2260 rc = vprintf(format, aptr);
2261 va_end(aptr);
2262
2263 if (color)
2264 color_end();
2265
2266 return (rc);
2267 }
2268
2269 /* PATH + 5 env vars + a NULL entry = 7 */
2270 #define ZPOOL_VDEV_SCRIPT_ENV_COUNT 7
2271
2272 /*
2273 * There's a few places where ZFS will call external scripts (like the script
2274 * in zpool.d/ and `zfs_prepare_disk`). These scripts are called with a
2275 * reduced $PATH, and some vdev specific environment vars set. This function
2276 * will allocate an populate the environment variable array that is passed to
2277 * these scripts. The user must free the arrays with zpool_vdev_free_env() when
2278 * they are done.
2279 *
2280 * The following env vars will be set (but value could be blank):
2281 *
2282 * POOL_NAME
2283 * VDEV_PATH
2284 * VDEV_UPATH
2285 * VDEV_ENC_SYSFS_PATH
2286 *
2287 * In addition, you can set an optional environment variable named 'opt_key'
2288 * to 'opt_val' if you want.
2289 *
2290 * Returns allocated env[] array on success, NULL otherwise.
2291 */
2292 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)2293 zpool_vdev_script_alloc_env(const char *pool_name,
2294 const char *vdev_path, const char *vdev_upath,
2295 const char *vdev_enc_sysfs_path, const char *opt_key, const char *opt_val)
2296 {
2297 char **env = NULL;
2298 int rc;
2299
2300 env = calloc(ZPOOL_VDEV_SCRIPT_ENV_COUNT, sizeof (*env));
2301 if (!env)
2302 return (NULL);
2303
2304 env[0] = strdup("PATH=/bin:/sbin:/usr/bin:/usr/sbin");
2305 if (!env[0])
2306 goto error;
2307
2308 /* Setup our custom environment variables */
2309 rc = asprintf(&env[1], "POOL_NAME=%s", pool_name ? pool_name : "");
2310 if (rc == -1) {
2311 env[1] = NULL;
2312 goto error;
2313 }
2314
2315 rc = asprintf(&env[2], "VDEV_PATH=%s", vdev_path ? vdev_path : "");
2316 if (rc == -1) {
2317 env[2] = NULL;
2318 goto error;
2319 }
2320
2321 rc = asprintf(&env[3], "VDEV_UPATH=%s", vdev_upath ? vdev_upath : "");
2322 if (rc == -1) {
2323 env[3] = NULL;
2324 goto error;
2325 }
2326
2327 rc = asprintf(&env[4], "VDEV_ENC_SYSFS_PATH=%s",
2328 vdev_enc_sysfs_path ? vdev_enc_sysfs_path : "");
2329 if (rc == -1) {
2330 env[4] = NULL;
2331 goto error;
2332 }
2333
2334 if (opt_key != NULL) {
2335 rc = asprintf(&env[5], "%s=%s", opt_key,
2336 opt_val ? opt_val : "");
2337 if (rc == -1) {
2338 env[5] = NULL;
2339 goto error;
2340 }
2341 }
2342
2343 return (env);
2344
2345 error:
2346 for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2347 free(env[i]);
2348
2349 free(env);
2350
2351 return (NULL);
2352 }
2353
2354 /*
2355 * Free the env[] array that was allocated by zpool_vdev_script_alloc_env().
2356 */
2357 void
zpool_vdev_script_free_env(char ** env)2358 zpool_vdev_script_free_env(char **env)
2359 {
2360 for (int i = 0; i < ZPOOL_VDEV_SCRIPT_ENV_COUNT; i++)
2361 free(env[i]);
2362
2363 free(env);
2364 }
2365
2366 /*
2367 * Prepare a disk by (optionally) running a program before labeling the disk.
2368 * This can be useful for installing disk firmware or doing some pre-flight
2369 * checks on the disk before it becomes part of the pool. The program run is
2370 * located at ZFSEXECDIR/zfs_prepare_disk
2371 * (E.x: /usr/local/libexec/zfs/zfs_prepare_disk).
2372 *
2373 * Return 0 on success, non-zero on failure.
2374 */
2375 int
zpool_prepare_disk(zpool_handle_t * zhp,nvlist_t * vdev_nv,const char * prepare_str,char ** lines[],int * lines_cnt)2376 zpool_prepare_disk(zpool_handle_t *zhp, nvlist_t *vdev_nv,
2377 const char *prepare_str, char **lines[], int *lines_cnt)
2378 {
2379 const char *script_path = ZFSEXECDIR "/zfs_prepare_disk";
2380 const char *pool_name;
2381 int rc = 0;
2382
2383 /* Path to script and a NULL entry */
2384 char *argv[2] = {(char *)script_path};
2385 char **env = NULL;
2386 const char *path = NULL, *enc_sysfs_path = NULL;
2387 char *upath;
2388 *lines_cnt = 0;
2389
2390 if (access(script_path, X_OK) != 0) {
2391 /* No script, nothing to do */
2392 return (0);
2393 }
2394
2395 (void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_PATH, &path);
2396 (void) nvlist_lookup_string(vdev_nv, ZPOOL_CONFIG_VDEV_ENC_SYSFS_PATH,
2397 &enc_sysfs_path);
2398
2399 upath = zfs_get_underlying_path(path);
2400 if (upath == NULL && path != NULL)
2401 upath = strdup(path);
2402 pool_name = zhp ? zpool_get_name(zhp) : NULL;
2403
2404 env = zpool_vdev_script_alloc_env(pool_name, path, upath,
2405 enc_sysfs_path, "VDEV_PREPARE", prepare_str);
2406
2407 free(upath);
2408
2409 if (env == NULL) {
2410 return (ENOMEM);
2411 }
2412
2413 rc = libzfs_run_process_get_stdout(script_path, argv, env, lines,
2414 lines_cnt);
2415
2416 zpool_vdev_script_free_env(env);
2417
2418 return (rc);
2419 }
2420
2421 /*
2422 * Optionally run a script and then label a disk. The script can be used to
2423 * prepare a disk for inclusion into the pool. For example, it might update
2424 * the disk's firmware or check its health.
2425 *
2426 * The 'name' provided is the short name, stripped of any leading
2427 * /dev path, and is passed to zpool_label_disk. vdev_nv is the nvlist for
2428 * the vdev. prepare_str is a string that gets passed as the VDEV_PREPARE
2429 * env variable to the script.
2430 *
2431 * The following env vars are passed to the script:
2432 *
2433 * POOL_NAME: The pool name (blank during zpool create)
2434 * VDEV_PREPARE: Reason why the disk is being prepared for inclusion:
2435 * "create", "add", "replace", or "autoreplace"
2436 * VDEV_PATH: Path to the disk
2437 * VDEV_UPATH: One of the 'underlying paths' to the disk. This is
2438 * useful for DM devices.
2439 * VDEV_ENC_SYSFS_PATH: Path to the disk's enclosure sysfs path, if available.
2440 *
2441 * Note, some of these values can be blank.
2442 *
2443 * Return 0 on success, non-zero otherwise.
2444 */
2445 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)2446 zpool_prepare_and_label_disk(libzfs_handle_t *hdl, zpool_handle_t *zhp,
2447 const char *name, nvlist_t *vdev_nv, const char *prepare_str,
2448 char **lines[], int *lines_cnt)
2449 {
2450 int rc;
2451 char vdev_path[MAXPATHLEN];
2452 (void) snprintf(vdev_path, sizeof (vdev_path), "%s/%s", DISK_ROOT,
2453 name);
2454
2455 /* zhp will be NULL when creating a pool */
2456 rc = zpool_prepare_disk(zhp, vdev_nv, prepare_str, lines, lines_cnt);
2457 if (rc != 0)
2458 return (rc);
2459
2460 rc = zpool_label_disk(hdl, zhp, name);
2461 return (rc);
2462 }
2463