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