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