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