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