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