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