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