xref: /freebsd/sys/contrib/openzfs/lib/libzfs/libzfs_sendrecv.c (revision 79ac3c12a714bcd3f2354c52d948aed9575c46d6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2011, 2020 by Delphix. All rights reserved.
25  * Copyright (c) 2012, Joyent, Inc. All rights reserved.
26  * Copyright (c) 2012 Pawel Jakub Dawidek <pawel@dawidek.net>.
27  * All rights reserved
28  * Copyright (c) 2013 Steven Hartland. All rights reserved.
29  * Copyright 2015, OmniTI Computer Consulting, Inc. All rights reserved.
30  * Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
31  * Copyright (c) 2018, loli10K <ezomori.nozomu@gmail.com>. All rights reserved.
32  * Copyright (c) 2019 Datto Inc.
33  */
34 
35 #include <assert.h>
36 #include <ctype.h>
37 #include <errno.h>
38 #include <libintl.h>
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <strings.h>
42 #include <unistd.h>
43 #include <stddef.h>
44 #include <fcntl.h>
45 #include <sys/mount.h>
46 #include <sys/mntent.h>
47 #include <sys/mnttab.h>
48 #include <sys/avl.h>
49 #include <sys/debug.h>
50 #include <sys/stat.h>
51 #include <pthread.h>
52 #include <umem.h>
53 #include <time.h>
54 
55 #include <libzfs.h>
56 #include <libzfs_core.h>
57 #include <libzutil.h>
58 
59 #include "zfs_namecheck.h"
60 #include "zfs_prop.h"
61 #include "zfs_fletcher.h"
62 #include "libzfs_impl.h"
63 #include <cityhash.h>
64 #include <zlib.h>
65 #include <sys/zio_checksum.h>
66 #include <sys/dsl_crypt.h>
67 #include <sys/ddt.h>
68 #include <sys/socket.h>
69 #include <sys/sha2.h>
70 
71 static int zfs_receive_impl(libzfs_handle_t *, const char *, const char *,
72     recvflags_t *, int, const char *, nvlist_t *, avl_tree_t *, char **,
73     const char *, nvlist_t *);
74 static int guid_to_name_redact_snaps(libzfs_handle_t *hdl, const char *parent,
75     uint64_t guid, boolean_t bookmark_ok, uint64_t *redact_snap_guids,
76     uint64_t num_redact_snaps, char *name);
77 static int guid_to_name(libzfs_handle_t *, const char *,
78     uint64_t, boolean_t, char *);
79 
80 typedef struct progress_arg {
81 	zfs_handle_t *pa_zhp;
82 	int pa_fd;
83 	boolean_t pa_parsable;
84 	boolean_t pa_estimate;
85 	int pa_verbosity;
86 } progress_arg_t;
87 
88 static int
89 dump_record(dmu_replay_record_t *drr, void *payload, int payload_len,
90     zio_cksum_t *zc, int outfd)
91 {
92 	ASSERT3U(offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum),
93 	    ==, sizeof (dmu_replay_record_t) - sizeof (zio_cksum_t));
94 	fletcher_4_incremental_native(drr,
95 	    offsetof(dmu_replay_record_t, drr_u.drr_checksum.drr_checksum), zc);
96 	if (drr->drr_type != DRR_BEGIN) {
97 		ASSERT(ZIO_CHECKSUM_IS_ZERO(&drr->drr_u.
98 		    drr_checksum.drr_checksum));
99 		drr->drr_u.drr_checksum.drr_checksum = *zc;
100 	}
101 	fletcher_4_incremental_native(&drr->drr_u.drr_checksum.drr_checksum,
102 	    sizeof (zio_cksum_t), zc);
103 	if (write(outfd, drr, sizeof (*drr)) == -1)
104 		return (errno);
105 	if (payload_len != 0) {
106 		fletcher_4_incremental_native(payload, payload_len, zc);
107 		if (write(outfd, payload, payload_len) == -1)
108 			return (errno);
109 	}
110 	return (0);
111 }
112 
113 /*
114  * Routines for dealing with the AVL tree of fs-nvlists
115  */
116 typedef struct fsavl_node {
117 	avl_node_t fn_node;
118 	nvlist_t *fn_nvfs;
119 	char *fn_snapname;
120 	uint64_t fn_guid;
121 } fsavl_node_t;
122 
123 static int
124 fsavl_compare(const void *arg1, const void *arg2)
125 {
126 	const fsavl_node_t *fn1 = (const fsavl_node_t *)arg1;
127 	const fsavl_node_t *fn2 = (const fsavl_node_t *)arg2;
128 
129 	return (TREE_CMP(fn1->fn_guid, fn2->fn_guid));
130 }
131 
132 /*
133  * Given the GUID of a snapshot, find its containing filesystem and
134  * (optionally) name.
135  */
136 static nvlist_t *
137 fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
138 {
139 	fsavl_node_t fn_find;
140 	fsavl_node_t *fn;
141 
142 	fn_find.fn_guid = snapguid;
143 
144 	fn = avl_find(avl, &fn_find, NULL);
145 	if (fn) {
146 		if (snapname)
147 			*snapname = fn->fn_snapname;
148 		return (fn->fn_nvfs);
149 	}
150 	return (NULL);
151 }
152 
153 static void
154 fsavl_destroy(avl_tree_t *avl)
155 {
156 	fsavl_node_t *fn;
157 	void *cookie;
158 
159 	if (avl == NULL)
160 		return;
161 
162 	cookie = NULL;
163 	while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
164 		free(fn);
165 	avl_destroy(avl);
166 	free(avl);
167 }
168 
169 /*
170  * Given an nvlist, produce an avl tree of snapshots, ordered by guid
171  */
172 static avl_tree_t *
173 fsavl_create(nvlist_t *fss)
174 {
175 	avl_tree_t *fsavl;
176 	nvpair_t *fselem = NULL;
177 
178 	if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
179 		return (NULL);
180 
181 	avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
182 	    offsetof(fsavl_node_t, fn_node));
183 
184 	while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
185 		nvlist_t *nvfs, *snaps;
186 		nvpair_t *snapelem = NULL;
187 
188 		nvfs = fnvpair_value_nvlist(fselem);
189 		snaps = fnvlist_lookup_nvlist(nvfs, "snaps");
190 
191 		while ((snapelem =
192 		    nvlist_next_nvpair(snaps, snapelem)) != NULL) {
193 			fsavl_node_t *fn;
194 			uint64_t guid;
195 
196 			guid = fnvpair_value_uint64(snapelem);
197 			if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
198 				fsavl_destroy(fsavl);
199 				return (NULL);
200 			}
201 			fn->fn_nvfs = nvfs;
202 			fn->fn_snapname = nvpair_name(snapelem);
203 			fn->fn_guid = guid;
204 
205 			/*
206 			 * Note: if there are multiple snaps with the
207 			 * same GUID, we ignore all but one.
208 			 */
209 			if (avl_find(fsavl, fn, NULL) == NULL)
210 				avl_add(fsavl, fn);
211 			else
212 				free(fn);
213 		}
214 	}
215 
216 	return (fsavl);
217 }
218 
219 /*
220  * Routines for dealing with the giant nvlist of fs-nvlists, etc.
221  */
222 typedef struct send_data {
223 	/*
224 	 * assigned inside every recursive call,
225 	 * restored from *_save on return:
226 	 *
227 	 * guid of fromsnap snapshot in parent dataset
228 	 * txg of fromsnap snapshot in current dataset
229 	 * txg of tosnap snapshot in current dataset
230 	 */
231 
232 	uint64_t parent_fromsnap_guid;
233 	uint64_t fromsnap_txg;
234 	uint64_t tosnap_txg;
235 
236 	/* the nvlists get accumulated during depth-first traversal */
237 	nvlist_t *parent_snaps;
238 	nvlist_t *fss;
239 	nvlist_t *snapprops;
240 	nvlist_t *snapholds;	/* user holds */
241 
242 	/* send-receive configuration, does not change during traversal */
243 	const char *fsname;
244 	const char *fromsnap;
245 	const char *tosnap;
246 	boolean_t recursive;
247 	boolean_t raw;
248 	boolean_t doall;
249 	boolean_t replicate;
250 	boolean_t skipmissing;
251 	boolean_t verbose;
252 	boolean_t backup;
253 	boolean_t seenfrom;
254 	boolean_t seento;
255 	boolean_t holds;	/* were holds requested with send -h */
256 	boolean_t props;
257 
258 	/*
259 	 * The header nvlist is of the following format:
260 	 * {
261 	 *   "tosnap" -> string
262 	 *   "fromsnap" -> string (if incremental)
263 	 *   "fss" -> {
264 	 *	id -> {
265 	 *
266 	 *	 "name" -> string (full name; for debugging)
267 	 *	 "parentfromsnap" -> number (guid of fromsnap in parent)
268 	 *
269 	 *	 "props" -> { name -> value (only if set here) }
270 	 *	 "snaps" -> { name (lastname) -> number (guid) }
271 	 *	 "snapprops" -> { name (lastname) -> { name -> value } }
272 	 *	 "snapholds" -> { name (lastname) -> { holdname -> crtime } }
273 	 *
274 	 *	 "origin" -> number (guid) (if clone)
275 	 *	 "is_encroot" -> boolean
276 	 *	 "sent" -> boolean (not on-disk)
277 	 *	}
278 	 *   }
279 	 * }
280 	 *
281 	 */
282 } send_data_t;
283 
284 static void
285 send_iterate_prop(zfs_handle_t *zhp, boolean_t received_only, nvlist_t *nv);
286 
287 static int
288 send_iterate_snap(zfs_handle_t *zhp, void *arg)
289 {
290 	send_data_t *sd = arg;
291 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
292 	uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
293 	char *snapname;
294 	nvlist_t *nv;
295 	boolean_t isfromsnap, istosnap, istosnapwithnofrom;
296 
297 	snapname = strrchr(zhp->zfs_name, '@')+1;
298 	isfromsnap = (sd->fromsnap != NULL &&
299 	    strcmp(sd->fromsnap, snapname) == 0);
300 	istosnap = (sd->tosnap != NULL && (strcmp(sd->tosnap, snapname) == 0));
301 	istosnapwithnofrom = (istosnap && sd->fromsnap == NULL);
302 
303 	if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
304 		if (sd->verbose) {
305 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
306 			    "skipping snapshot %s because it was created "
307 			    "after the destination snapshot (%s)\n"),
308 			    zhp->zfs_name, sd->tosnap);
309 		}
310 		zfs_close(zhp);
311 		return (0);
312 	}
313 
314 	fnvlist_add_uint64(sd->parent_snaps, snapname, guid);
315 	/*
316 	 * NB: if there is no fromsnap here (it's a newly created fs in
317 	 * an incremental replication), we will substitute the tosnap.
318 	 */
319 	if (isfromsnap || (sd->parent_fromsnap_guid == 0 && istosnap)) {
320 		sd->parent_fromsnap_guid = guid;
321 	}
322 
323 	if (!sd->recursive) {
324 
325 		/*
326 		 * To allow a doall stream to work properly
327 		 * with a NULL fromsnap
328 		 */
329 		if (sd->doall && sd->fromsnap == NULL && !sd->seenfrom) {
330 			sd->seenfrom = B_TRUE;
331 		}
332 
333 		if (!sd->seenfrom && isfromsnap) {
334 			sd->seenfrom = B_TRUE;
335 			zfs_close(zhp);
336 			return (0);
337 		}
338 
339 		if ((sd->seento || !sd->seenfrom) && !istosnapwithnofrom) {
340 			zfs_close(zhp);
341 			return (0);
342 		}
343 
344 		if (istosnap)
345 			sd->seento = B_TRUE;
346 	}
347 
348 	nv = fnvlist_alloc();
349 	send_iterate_prop(zhp, sd->backup, nv);
350 	fnvlist_add_nvlist(sd->snapprops, snapname, nv);
351 	fnvlist_free(nv);
352 	if (sd->holds) {
353 		nvlist_t *holds = fnvlist_alloc();
354 		int err = lzc_get_holds(zhp->zfs_name, &holds);
355 		if (err == 0) {
356 			fnvlist_add_nvlist(sd->snapholds, snapname, holds);
357 		}
358 		fnvlist_free(holds);
359 	}
360 
361 	zfs_close(zhp);
362 	return (0);
363 }
364 
365 static void
366 send_iterate_prop(zfs_handle_t *zhp, boolean_t received_only, nvlist_t *nv)
367 {
368 	nvlist_t *props = NULL;
369 	nvpair_t *elem = NULL;
370 
371 	if (received_only)
372 		props = zfs_get_recvd_props(zhp);
373 	else
374 		props = zhp->zfs_props;
375 
376 	while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
377 		char *propname = nvpair_name(elem);
378 		zfs_prop_t prop = zfs_name_to_prop(propname);
379 		nvlist_t *propnv;
380 
381 		if (!zfs_prop_user(propname)) {
382 			/*
383 			 * Realistically, this should never happen.  However,
384 			 * we want the ability to add DSL properties without
385 			 * needing to make incompatible version changes.  We
386 			 * need to ignore unknown properties to allow older
387 			 * software to still send datasets containing these
388 			 * properties, with the unknown properties elided.
389 			 */
390 			if (prop == ZPROP_INVAL)
391 				continue;
392 
393 			if (zfs_prop_readonly(prop))
394 				continue;
395 		}
396 
397 		verify(nvpair_value_nvlist(elem, &propnv) == 0);
398 		if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
399 		    prop == ZFS_PROP_REFQUOTA ||
400 		    prop == ZFS_PROP_REFRESERVATION) {
401 			char *source;
402 			uint64_t value;
403 			verify(nvlist_lookup_uint64(propnv,
404 			    ZPROP_VALUE, &value) == 0);
405 			if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
406 				continue;
407 			/*
408 			 * May have no source before SPA_VERSION_RECVD_PROPS,
409 			 * but is still modifiable.
410 			 */
411 			if (nvlist_lookup_string(propnv,
412 			    ZPROP_SOURCE, &source) == 0) {
413 				if ((strcmp(source, zhp->zfs_name) != 0) &&
414 				    (strcmp(source,
415 				    ZPROP_SOURCE_VAL_RECVD) != 0))
416 					continue;
417 			}
418 		} else {
419 			char *source;
420 			if (nvlist_lookup_string(propnv,
421 			    ZPROP_SOURCE, &source) != 0)
422 				continue;
423 			if ((strcmp(source, zhp->zfs_name) != 0) &&
424 			    (strcmp(source, ZPROP_SOURCE_VAL_RECVD) != 0))
425 				continue;
426 		}
427 
428 		if (zfs_prop_user(propname) ||
429 		    zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
430 			char *value;
431 			value = fnvlist_lookup_string(propnv, ZPROP_VALUE);
432 			fnvlist_add_string(nv, propname, value);
433 		} else {
434 			uint64_t value;
435 			value = fnvlist_lookup_uint64(propnv, ZPROP_VALUE);
436 			fnvlist_add_uint64(nv, propname, value);
437 		}
438 	}
439 }
440 
441 /*
442  * returns snapshot creation txg
443  * and returns 0 if the snapshot does not exist
444  */
445 static uint64_t
446 get_snap_txg(libzfs_handle_t *hdl, const char *fs, const char *snap)
447 {
448 	char name[ZFS_MAX_DATASET_NAME_LEN];
449 	uint64_t txg = 0;
450 
451 	if (fs == NULL || fs[0] == '\0' || snap == NULL || snap[0] == '\0')
452 		return (txg);
453 
454 	(void) snprintf(name, sizeof (name), "%s@%s", fs, snap);
455 	if (zfs_dataset_exists(hdl, name, ZFS_TYPE_SNAPSHOT)) {
456 		zfs_handle_t *zhp = zfs_open(hdl, name, ZFS_TYPE_SNAPSHOT);
457 		if (zhp != NULL) {
458 			txg = zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG);
459 			zfs_close(zhp);
460 		}
461 	}
462 
463 	return (txg);
464 }
465 
466 /*
467  * recursively generate nvlists describing datasets.  See comment
468  * for the data structure send_data_t above for description of contents
469  * of the nvlist.
470  */
471 static int
472 send_iterate_fs(zfs_handle_t *zhp, void *arg)
473 {
474 	send_data_t *sd = arg;
475 	nvlist_t *nvfs = NULL, *nv = NULL;
476 	int rv = 0;
477 	uint64_t min_txg = 0, max_txg = 0;
478 	uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
479 	uint64_t fromsnap_txg_save = sd->fromsnap_txg;
480 	uint64_t tosnap_txg_save = sd->tosnap_txg;
481 	uint64_t txg = zhp->zfs_dmustats.dds_creation_txg;
482 	uint64_t guid = zhp->zfs_dmustats.dds_guid;
483 	uint64_t fromsnap_txg, tosnap_txg;
484 	char guidstring[64];
485 
486 	fromsnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->fromsnap);
487 	if (fromsnap_txg != 0)
488 		sd->fromsnap_txg = fromsnap_txg;
489 
490 	tosnap_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name, sd->tosnap);
491 	if (tosnap_txg != 0)
492 		sd->tosnap_txg = tosnap_txg;
493 
494 	/*
495 	 * on the send side, if the current dataset does not have tosnap,
496 	 * perform two additional checks:
497 	 *
498 	 * - skip sending the current dataset if it was created later than
499 	 *   the parent tosnap
500 	 * - return error if the current dataset was created earlier than
501 	 *   the parent tosnap, unless --skip-missing specified. Then
502 	 *   just print a warning
503 	 */
504 	if (sd->tosnap != NULL && tosnap_txg == 0) {
505 		if (sd->tosnap_txg != 0 && txg > sd->tosnap_txg) {
506 			if (sd->verbose) {
507 				(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
508 				    "skipping dataset %s: snapshot %s does "
509 				    "not exist\n"), zhp->zfs_name, sd->tosnap);
510 			}
511 		} else if (sd->skipmissing) {
512 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
513 			    "WARNING: skipping dataset %s and its children:"
514 			    " snapshot %s does not exist\n"),
515 			    zhp->zfs_name, sd->tosnap);
516 		} else {
517 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
518 			    "cannot send %s@%s%s: snapshot %s@%s does not "
519 			    "exist\n"), sd->fsname, sd->tosnap, sd->recursive ?
520 			    dgettext(TEXT_DOMAIN, " recursively") : "",
521 			    zhp->zfs_name, sd->tosnap);
522 			rv = EZFS_NOENT;
523 		}
524 		goto out;
525 	}
526 
527 	nvfs = fnvlist_alloc();
528 	fnvlist_add_string(nvfs, "name", zhp->zfs_name);
529 	fnvlist_add_uint64(nvfs, "parentfromsnap",
530 	    sd->parent_fromsnap_guid);
531 
532 	if (zhp->zfs_dmustats.dds_origin[0]) {
533 		zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
534 		    zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
535 		if (origin == NULL) {
536 			rv = -1;
537 			goto out;
538 		}
539 		fnvlist_add_uint64(nvfs, "origin",
540 		    origin->zfs_dmustats.dds_guid);
541 
542 		zfs_close(origin);
543 	}
544 
545 	/* iterate over props */
546 	if (sd->props || sd->backup || sd->recursive) {
547 		nv = fnvlist_alloc();
548 		send_iterate_prop(zhp, sd->backup, nv);
549 	}
550 	if (zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) != ZIO_CRYPT_OFF) {
551 		boolean_t encroot;
552 
553 		/* determine if this dataset is an encryption root */
554 		if (zfs_crypto_get_encryption_root(zhp, &encroot, NULL) != 0) {
555 			rv = -1;
556 			goto out;
557 		}
558 
559 		if (encroot)
560 			fnvlist_add_boolean(nvfs, "is_encroot");
561 
562 		/*
563 		 * Encrypted datasets can only be sent with properties if
564 		 * the raw flag is specified because the receive side doesn't
565 		 * currently have a mechanism for recursively asking the user
566 		 * for new encryption parameters.
567 		 */
568 		if (!sd->raw) {
569 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
570 			    "cannot send %s@%s: encrypted dataset %s may not "
571 			    "be sent with properties without the raw flag\n"),
572 			    sd->fsname, sd->tosnap, zhp->zfs_name);
573 			rv = -1;
574 			goto out;
575 		}
576 
577 	}
578 
579 	if (nv != NULL)
580 		fnvlist_add_nvlist(nvfs, "props", nv);
581 
582 	/* iterate over snaps, and set sd->parent_fromsnap_guid */
583 	sd->parent_fromsnap_guid = 0;
584 	sd->parent_snaps = fnvlist_alloc();
585 	sd->snapprops = fnvlist_alloc();
586 	if (sd->holds)
587 		sd->snapholds = fnvlist_alloc();
588 
589 	/*
590 	 * If this is a "doall" send, a replicate send or we're just trying
591 	 * to gather a list of previous snapshots, iterate through all the
592 	 * snaps in the txg range. Otherwise just look at the one we're
593 	 * interested in.
594 	 */
595 	if (sd->doall || sd->replicate || sd->tosnap == NULL) {
596 		if (!sd->replicate && fromsnap_txg != 0)
597 			min_txg = fromsnap_txg;
598 		if (!sd->replicate && tosnap_txg != 0)
599 			max_txg = tosnap_txg;
600 		(void) zfs_iter_snapshots_sorted(zhp, send_iterate_snap, sd,
601 		    min_txg, max_txg);
602 	} else {
603 		char snapname[MAXPATHLEN] = { 0 };
604 		zfs_handle_t *snap;
605 
606 		(void) snprintf(snapname, sizeof (snapname), "%s@%s",
607 		    zhp->zfs_name, sd->tosnap);
608 		if (sd->fromsnap != NULL)
609 			sd->seenfrom = B_TRUE;
610 		snap = zfs_open(zhp->zfs_hdl, snapname,
611 		    ZFS_TYPE_SNAPSHOT);
612 		if (snap != NULL)
613 			(void) send_iterate_snap(snap, sd);
614 	}
615 
616 	fnvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps);
617 	fnvlist_add_nvlist(nvfs, "snapprops", sd->snapprops);
618 	if (sd->holds)
619 		fnvlist_add_nvlist(nvfs, "snapholds", sd->snapholds);
620 	fnvlist_free(sd->parent_snaps);
621 	fnvlist_free(sd->snapprops);
622 	fnvlist_free(sd->snapholds);
623 
624 	/* Do not allow the size of the properties list to exceed the limit */
625 	if ((fnvlist_size(nvfs) + fnvlist_size(sd->fss)) >
626 	    zhp->zfs_hdl->libzfs_max_nvlist) {
627 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
628 		    "warning: cannot send %s@%s: the size of the list of "
629 		    "snapshots and properties is too large to be received "
630 		    "successfully.\n"
631 		    "Select a smaller number of snapshots to send.\n"),
632 		    zhp->zfs_name, sd->tosnap);
633 		rv = EZFS_NOSPC;
634 		goto out;
635 	}
636 	/* add this fs to nvlist */
637 	(void) snprintf(guidstring, sizeof (guidstring),
638 	    "0x%llx", (longlong_t)guid);
639 	fnvlist_add_nvlist(sd->fss, guidstring, nvfs);
640 
641 	/* iterate over children */
642 	if (sd->recursive)
643 		rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
644 
645 out:
646 	sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
647 	sd->fromsnap_txg = fromsnap_txg_save;
648 	sd->tosnap_txg = tosnap_txg_save;
649 	fnvlist_free(nv);
650 	fnvlist_free(nvfs);
651 
652 	zfs_close(zhp);
653 	return (rv);
654 }
655 
656 static int
657 gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
658     const char *tosnap, boolean_t recursive, boolean_t raw, boolean_t doall,
659     boolean_t replicate, boolean_t skipmissing, boolean_t verbose,
660     boolean_t backup, boolean_t holds, boolean_t props, nvlist_t **nvlp,
661     avl_tree_t **avlp)
662 {
663 	zfs_handle_t *zhp;
664 	send_data_t sd = { 0 };
665 	int error;
666 
667 	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
668 	if (zhp == NULL)
669 		return (EZFS_BADTYPE);
670 
671 	sd.fss = fnvlist_alloc();
672 	sd.fsname = fsname;
673 	sd.fromsnap = fromsnap;
674 	sd.tosnap = tosnap;
675 	sd.recursive = recursive;
676 	sd.raw = raw;
677 	sd.doall = doall;
678 	sd.replicate = replicate;
679 	sd.skipmissing = skipmissing;
680 	sd.verbose = verbose;
681 	sd.backup = backup;
682 	sd.holds = holds;
683 	sd.props = props;
684 
685 	if ((error = send_iterate_fs(zhp, &sd)) != 0) {
686 		fnvlist_free(sd.fss);
687 		if (avlp != NULL)
688 			*avlp = NULL;
689 		*nvlp = NULL;
690 		return (error);
691 	}
692 
693 	if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
694 		fnvlist_free(sd.fss);
695 		*nvlp = NULL;
696 		return (EZFS_NOMEM);
697 	}
698 
699 	*nvlp = sd.fss;
700 	return (0);
701 }
702 
703 /*
704  * Routines specific to "zfs send"
705  */
706 typedef struct send_dump_data {
707 	/* these are all just the short snapname (the part after the @) */
708 	const char *fromsnap;
709 	const char *tosnap;
710 	char prevsnap[ZFS_MAX_DATASET_NAME_LEN];
711 	uint64_t prevsnap_obj;
712 	boolean_t seenfrom, seento, replicate, doall, fromorigin;
713 	boolean_t dryrun, parsable, progress, embed_data, std_out;
714 	boolean_t large_block, compress, raw, holds;
715 	int outfd;
716 	boolean_t err;
717 	nvlist_t *fss;
718 	nvlist_t *snapholds;
719 	avl_tree_t *fsavl;
720 	snapfilter_cb_t *filter_cb;
721 	void *filter_cb_arg;
722 	nvlist_t *debugnv;
723 	char holdtag[ZFS_MAX_DATASET_NAME_LEN];
724 	int cleanup_fd;
725 	int verbosity;
726 	uint64_t size;
727 } send_dump_data_t;
728 
729 static int
730 zfs_send_space(zfs_handle_t *zhp, const char *snapname, const char *from,
731     enum lzc_send_flags flags, uint64_t *spacep)
732 {
733 	libzfs_handle_t *hdl = zhp->zfs_hdl;
734 	int error;
735 
736 	assert(snapname != NULL);
737 	error = lzc_send_space(snapname, from, flags, spacep);
738 
739 	if (error != 0) {
740 		char errbuf[1024];
741 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
742 		    "warning: cannot estimate space for '%s'"), snapname);
743 
744 		switch (error) {
745 		case EXDEV:
746 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
747 			    "not an earlier snapshot from the same fs"));
748 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
749 
750 		case ENOENT:
751 			if (zfs_dataset_exists(hdl, snapname,
752 			    ZFS_TYPE_SNAPSHOT)) {
753 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
754 				    "incremental source (%s) does not exist"),
755 				    snapname);
756 			}
757 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
758 
759 		case EDQUOT:
760 		case EFBIG:
761 		case EIO:
762 		case ENOLINK:
763 		case ENOSPC:
764 		case ENOSTR:
765 		case ENXIO:
766 		case EPIPE:
767 		case ERANGE:
768 		case EFAULT:
769 		case EROFS:
770 		case EINVAL:
771 			zfs_error_aux(hdl, "%s", strerror(error));
772 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
773 
774 		default:
775 			return (zfs_standard_error(hdl, error, errbuf));
776 		}
777 	}
778 
779 	return (0);
780 }
781 
782 /*
783  * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
784  * NULL) to the file descriptor specified by outfd.
785  */
786 static int
787 dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, uint64_t fromsnap_obj,
788     boolean_t fromorigin, int outfd, enum lzc_send_flags flags,
789     nvlist_t *debugnv)
790 {
791 	zfs_cmd_t zc = {"\0"};
792 	libzfs_handle_t *hdl = zhp->zfs_hdl;
793 	nvlist_t *thisdbg;
794 
795 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
796 	assert(fromsnap_obj == 0 || !fromorigin);
797 
798 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
799 	zc.zc_cookie = outfd;
800 	zc.zc_obj = fromorigin;
801 	zc.zc_sendobj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
802 	zc.zc_fromobj = fromsnap_obj;
803 	zc.zc_flags = flags;
804 
805 	thisdbg = fnvlist_alloc();
806 	if (fromsnap && fromsnap[0] != '\0') {
807 		fnvlist_add_string(thisdbg, "fromsnap", fromsnap);
808 	}
809 
810 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND, &zc) != 0) {
811 		char errbuf[1024];
812 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
813 		    "warning: cannot send '%s'"), zhp->zfs_name);
814 
815 		fnvlist_add_uint64(thisdbg, "error", errno);
816 		if (debugnv) {
817 			fnvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg);
818 		}
819 		fnvlist_free(thisdbg);
820 
821 		switch (errno) {
822 		case EXDEV:
823 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
824 			    "not an earlier snapshot from the same fs"));
825 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
826 
827 		case EACCES:
828 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
829 			    "source key must be loaded"));
830 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
831 
832 		case ENOENT:
833 			if (zfs_dataset_exists(hdl, zc.zc_name,
834 			    ZFS_TYPE_SNAPSHOT)) {
835 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
836 				    "incremental source (@%s) does not exist"),
837 				    zc.zc_value);
838 			}
839 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
840 
841 		case EDQUOT:
842 		case EFBIG:
843 		case EIO:
844 		case ENOLINK:
845 		case ENOSPC:
846 		case ENOSTR:
847 		case ENXIO:
848 		case EPIPE:
849 		case ERANGE:
850 		case EFAULT:
851 		case EROFS:
852 		case EINVAL:
853 			zfs_error_aux(hdl, "%s", strerror(errno));
854 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
855 
856 		default:
857 			return (zfs_standard_error(hdl, errno, errbuf));
858 		}
859 	}
860 
861 	if (debugnv)
862 		fnvlist_add_nvlist(debugnv, zhp->zfs_name, thisdbg);
863 	fnvlist_free(thisdbg);
864 
865 	return (0);
866 }
867 
868 static void
869 gather_holds(zfs_handle_t *zhp, send_dump_data_t *sdd)
870 {
871 	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
872 
873 	/*
874 	 * zfs_send() only sets snapholds for sends that need them,
875 	 * e.g. replication and doall.
876 	 */
877 	if (sdd->snapholds == NULL)
878 		return;
879 
880 	fnvlist_add_string(sdd->snapholds, zhp->zfs_name, sdd->holdtag);
881 }
882 
883 int
884 zfs_send_progress(zfs_handle_t *zhp, int fd, uint64_t *bytes_written,
885     uint64_t *blocks_visited)
886 {
887 	zfs_cmd_t zc = {"\0"};
888 
889 	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
890 	zc.zc_cookie = fd;
891 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_SEND_PROGRESS, &zc) != 0)
892 		return (errno);
893 	if (bytes_written != NULL)
894 		*bytes_written = zc.zc_cookie;
895 	if (blocks_visited != NULL)
896 		*blocks_visited = zc.zc_objset_type;
897 	return (0);
898 }
899 
900 static void *
901 send_progress_thread(void *arg)
902 {
903 	progress_arg_t *pa = arg;
904 	zfs_handle_t *zhp = pa->pa_zhp;
905 	uint64_t bytes;
906 	uint64_t blocks;
907 	char buf[16];
908 	time_t t;
909 	struct tm *tm;
910 	boolean_t firstloop = B_TRUE;
911 
912 	/*
913 	 * Print the progress from ZFS_IOC_SEND_PROGRESS every second.
914 	 */
915 	for (;;) {
916 		int err;
917 		(void) sleep(1);
918 		if ((err = zfs_send_progress(zhp, pa->pa_fd, &bytes,
919 		    &blocks)) != 0) {
920 			if (err == EINTR || err == ENOENT)
921 				return ((void *)0);
922 			return ((void *)(uintptr_t)err);
923 		}
924 
925 		if (firstloop && !pa->pa_parsable) {
926 			(void) fprintf(stderr,
927 			    "TIME       %s   %sSNAPSHOT %s\n",
928 			    pa->pa_estimate ? "BYTES" : " SENT",
929 			    pa->pa_verbosity >= 2 ? "   BLOCKS    " : "",
930 			    zhp->zfs_name);
931 			firstloop = B_FALSE;
932 		}
933 
934 		(void) time(&t);
935 		tm = localtime(&t);
936 
937 		if (pa->pa_verbosity >= 2 && pa->pa_parsable) {
938 			(void) fprintf(stderr,
939 			    "%02d:%02d:%02d\t%llu\t%llu\t%s\n",
940 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
941 			    (u_longlong_t)bytes, (u_longlong_t)blocks,
942 			    zhp->zfs_name);
943 		} else if (pa->pa_verbosity >= 2) {
944 			zfs_nicenum(bytes, buf, sizeof (buf));
945 			(void) fprintf(stderr,
946 			    "%02d:%02d:%02d   %5s    %8llu    %s\n",
947 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
948 			    buf, (u_longlong_t)blocks, zhp->zfs_name);
949 		} else if (pa->pa_parsable) {
950 			(void) fprintf(stderr, "%02d:%02d:%02d\t%llu\t%s\n",
951 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
952 			    (u_longlong_t)bytes, zhp->zfs_name);
953 		} else {
954 			zfs_nicebytes(bytes, buf, sizeof (buf));
955 			(void) fprintf(stderr, "%02d:%02d:%02d   %5s   %s\n",
956 			    tm->tm_hour, tm->tm_min, tm->tm_sec,
957 			    buf, zhp->zfs_name);
958 		}
959 	}
960 }
961 
962 static void
963 send_print_verbose(FILE *fout, const char *tosnap, const char *fromsnap,
964     uint64_t size, boolean_t parsable)
965 {
966 	if (parsable) {
967 		if (fromsnap != NULL) {
968 			(void) fprintf(fout, "incremental\t%s\t%s",
969 			    fromsnap, tosnap);
970 		} else {
971 			(void) fprintf(fout, "full\t%s",
972 			    tosnap);
973 		}
974 	} else {
975 		if (fromsnap != NULL) {
976 			if (strchr(fromsnap, '@') == NULL &&
977 			    strchr(fromsnap, '#') == NULL) {
978 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
979 				    "send from @%s to %s"),
980 				    fromsnap, tosnap);
981 			} else {
982 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
983 				    "send from %s to %s"),
984 				    fromsnap, tosnap);
985 			}
986 		} else {
987 			(void) fprintf(fout, dgettext(TEXT_DOMAIN,
988 			    "full send of %s"),
989 			    tosnap);
990 		}
991 	}
992 
993 	if (parsable) {
994 		(void) fprintf(fout, "\t%llu",
995 		    (longlong_t)size);
996 	} else if (size != 0) {
997 		char buf[16];
998 		zfs_nicebytes(size, buf, sizeof (buf));
999 		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1000 		    " estimated size is %s"), buf);
1001 	}
1002 	(void) fprintf(fout, "\n");
1003 }
1004 
1005 static int
1006 dump_snapshot(zfs_handle_t *zhp, void *arg)
1007 {
1008 	send_dump_data_t *sdd = arg;
1009 	progress_arg_t pa = { 0 };
1010 	pthread_t tid;
1011 	char *thissnap;
1012 	enum lzc_send_flags flags = 0;
1013 	int err;
1014 	boolean_t isfromsnap, istosnap, fromorigin;
1015 	boolean_t exclude = B_FALSE;
1016 	FILE *fout = sdd->std_out ? stdout : stderr;
1017 
1018 	err = 0;
1019 	thissnap = strchr(zhp->zfs_name, '@') + 1;
1020 	isfromsnap = (sdd->fromsnap != NULL &&
1021 	    strcmp(sdd->fromsnap, thissnap) == 0);
1022 
1023 	if (!sdd->seenfrom && isfromsnap) {
1024 		gather_holds(zhp, sdd);
1025 		sdd->seenfrom = B_TRUE;
1026 		(void) strlcpy(sdd->prevsnap, thissnap,
1027 		    sizeof (sdd->prevsnap));
1028 		sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1029 		zfs_close(zhp);
1030 		return (0);
1031 	}
1032 
1033 	if (sdd->seento || !sdd->seenfrom) {
1034 		zfs_close(zhp);
1035 		return (0);
1036 	}
1037 
1038 	istosnap = (strcmp(sdd->tosnap, thissnap) == 0);
1039 	if (istosnap)
1040 		sdd->seento = B_TRUE;
1041 
1042 	if (sdd->large_block)
1043 		flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1044 	if (sdd->embed_data)
1045 		flags |= LZC_SEND_FLAG_EMBED_DATA;
1046 	if (sdd->compress)
1047 		flags |= LZC_SEND_FLAG_COMPRESS;
1048 	if (sdd->raw)
1049 		flags |= LZC_SEND_FLAG_RAW;
1050 
1051 	if (!sdd->doall && !isfromsnap && !istosnap) {
1052 		if (sdd->replicate) {
1053 			char *snapname;
1054 			nvlist_t *snapprops;
1055 			/*
1056 			 * Filter out all intermediate snapshots except origin
1057 			 * snapshots needed to replicate clones.
1058 			 */
1059 			nvlist_t *nvfs = fsavl_find(sdd->fsavl,
1060 			    zhp->zfs_dmustats.dds_guid, &snapname);
1061 
1062 			snapprops = fnvlist_lookup_nvlist(nvfs, "snapprops");
1063 			snapprops = fnvlist_lookup_nvlist(snapprops, thissnap);
1064 			exclude = !nvlist_exists(snapprops, "is_clone_origin");
1065 		} else {
1066 			exclude = B_TRUE;
1067 		}
1068 	}
1069 
1070 	/*
1071 	 * If a filter function exists, call it to determine whether
1072 	 * this snapshot will be sent.
1073 	 */
1074 	if (exclude || (sdd->filter_cb != NULL &&
1075 	    sdd->filter_cb(zhp, sdd->filter_cb_arg) == B_FALSE)) {
1076 		/*
1077 		 * This snapshot is filtered out.  Don't send it, and don't
1078 		 * set prevsnap_obj, so it will be as if this snapshot didn't
1079 		 * exist, and the next accepted snapshot will be sent as
1080 		 * an incremental from the last accepted one, or as the
1081 		 * first (and full) snapshot in the case of a replication,
1082 		 * non-incremental send.
1083 		 */
1084 		zfs_close(zhp);
1085 		return (0);
1086 	}
1087 
1088 	gather_holds(zhp, sdd);
1089 	fromorigin = sdd->prevsnap[0] == '\0' &&
1090 	    (sdd->fromorigin || sdd->replicate);
1091 
1092 	if (sdd->verbosity != 0) {
1093 		uint64_t size = 0;
1094 		char fromds[ZFS_MAX_DATASET_NAME_LEN];
1095 
1096 		if (sdd->prevsnap[0] != '\0') {
1097 			(void) strlcpy(fromds, zhp->zfs_name, sizeof (fromds));
1098 			*(strchr(fromds, '@') + 1) = '\0';
1099 			(void) strlcat(fromds, sdd->prevsnap, sizeof (fromds));
1100 		}
1101 		if (zfs_send_space(zhp, zhp->zfs_name,
1102 		    sdd->prevsnap[0] ? fromds : NULL, flags, &size) != 0) {
1103 			size = 0; /* cannot estimate send space */
1104 		} else {
1105 			send_print_verbose(fout, zhp->zfs_name,
1106 			    sdd->prevsnap[0] ? sdd->prevsnap : NULL,
1107 			    size, sdd->parsable);
1108 		}
1109 		sdd->size += size;
1110 	}
1111 
1112 	if (!sdd->dryrun) {
1113 		/*
1114 		 * If progress reporting is requested, spawn a new thread to
1115 		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1116 		 */
1117 		if (sdd->progress) {
1118 			pa.pa_zhp = zhp;
1119 			pa.pa_fd = sdd->outfd;
1120 			pa.pa_parsable = sdd->parsable;
1121 			pa.pa_estimate = B_FALSE;
1122 			pa.pa_verbosity = sdd->verbosity;
1123 
1124 			if ((err = pthread_create(&tid, NULL,
1125 			    send_progress_thread, &pa)) != 0) {
1126 				zfs_close(zhp);
1127 				return (err);
1128 			}
1129 		}
1130 
1131 		err = dump_ioctl(zhp, sdd->prevsnap, sdd->prevsnap_obj,
1132 		    fromorigin, sdd->outfd, flags, sdd->debugnv);
1133 
1134 		if (sdd->progress) {
1135 			void *status = NULL;
1136 			(void) pthread_cancel(tid);
1137 			(void) pthread_join(tid, &status);
1138 			int error = (int)(uintptr_t)status;
1139 			if (error != 0 && status != PTHREAD_CANCELED) {
1140 				char errbuf[1024];
1141 				(void) snprintf(errbuf, sizeof (errbuf),
1142 				    dgettext(TEXT_DOMAIN,
1143 				    "progress thread exited nonzero"));
1144 				return (zfs_standard_error(zhp->zfs_hdl, error,
1145 				    errbuf));
1146 			}
1147 		}
1148 	}
1149 
1150 	(void) strcpy(sdd->prevsnap, thissnap);
1151 	sdd->prevsnap_obj = zfs_prop_get_int(zhp, ZFS_PROP_OBJSETID);
1152 	zfs_close(zhp);
1153 	return (err);
1154 }
1155 
1156 static int
1157 dump_filesystem(zfs_handle_t *zhp, void *arg)
1158 {
1159 	int rv = 0;
1160 	send_dump_data_t *sdd = arg;
1161 	boolean_t missingfrom = B_FALSE;
1162 	zfs_cmd_t zc = {"\0"};
1163 	uint64_t min_txg = 0, max_txg = 0;
1164 
1165 	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1166 	    zhp->zfs_name, sdd->tosnap);
1167 	if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1168 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1169 		    "WARNING: could not send %s@%s: does not exist\n"),
1170 		    zhp->zfs_name, sdd->tosnap);
1171 		sdd->err = B_TRUE;
1172 		return (0);
1173 	}
1174 
1175 	if (sdd->replicate && sdd->fromsnap) {
1176 		/*
1177 		 * If this fs does not have fromsnap, and we're doing
1178 		 * recursive, we need to send a full stream from the
1179 		 * beginning (or an incremental from the origin if this
1180 		 * is a clone).  If we're doing non-recursive, then let
1181 		 * them get the error.
1182 		 */
1183 		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
1184 		    zhp->zfs_name, sdd->fromsnap);
1185 		if (zfs_ioctl(zhp->zfs_hdl,
1186 		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
1187 			missingfrom = B_TRUE;
1188 		}
1189 	}
1190 
1191 	sdd->seenfrom = sdd->seento = sdd->prevsnap[0] = 0;
1192 	sdd->prevsnap_obj = 0;
1193 	if (sdd->fromsnap == NULL || missingfrom)
1194 		sdd->seenfrom = B_TRUE;
1195 
1196 
1197 
1198 	/*
1199 	 * Iterate through all snapshots and process the ones we will be
1200 	 * sending. If we only have a "from" and "to" snapshot to deal
1201 	 * with, we can avoid iterating through all the other snapshots.
1202 	 */
1203 	if (sdd->doall || sdd->replicate || sdd->tosnap == NULL) {
1204 		if (!sdd->replicate && sdd->fromsnap != NULL)
1205 			min_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name,
1206 			    sdd->fromsnap);
1207 		if (!sdd->replicate && sdd->tosnap != NULL)
1208 			max_txg = get_snap_txg(zhp->zfs_hdl, zhp->zfs_name,
1209 			    sdd->tosnap);
1210 		rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg,
1211 		    min_txg, max_txg);
1212 	} else {
1213 		char snapname[MAXPATHLEN] = { 0 };
1214 		zfs_handle_t *snap;
1215 
1216 		if (!sdd->seenfrom) {
1217 			(void) snprintf(snapname, sizeof (snapname),
1218 			    "%s@%s", zhp->zfs_name, sdd->fromsnap);
1219 			snap = zfs_open(zhp->zfs_hdl, snapname,
1220 			    ZFS_TYPE_SNAPSHOT);
1221 			if (snap != NULL)
1222 				rv = dump_snapshot(snap, sdd);
1223 			else
1224 				rv = -1;
1225 		}
1226 
1227 		if (rv == 0) {
1228 			(void) snprintf(snapname, sizeof (snapname),
1229 			    "%s@%s", zhp->zfs_name, sdd->tosnap);
1230 			snap = zfs_open(zhp->zfs_hdl, snapname,
1231 			    ZFS_TYPE_SNAPSHOT);
1232 			if (snap != NULL)
1233 				rv = dump_snapshot(snap, sdd);
1234 			else
1235 				rv = -1;
1236 		}
1237 	}
1238 
1239 	if (!sdd->seenfrom) {
1240 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1241 		    "WARNING: could not send %s@%s:\n"
1242 		    "incremental source (%s@%s) does not exist\n"),
1243 		    zhp->zfs_name, sdd->tosnap,
1244 		    zhp->zfs_name, sdd->fromsnap);
1245 		sdd->err = B_TRUE;
1246 	} else if (!sdd->seento) {
1247 		if (sdd->fromsnap) {
1248 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1249 			    "WARNING: could not send %s@%s:\n"
1250 			    "incremental source (%s@%s) "
1251 			    "is not earlier than it\n"),
1252 			    zhp->zfs_name, sdd->tosnap,
1253 			    zhp->zfs_name, sdd->fromsnap);
1254 		} else {
1255 			(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
1256 			    "WARNING: "
1257 			    "could not send %s@%s: does not exist\n"),
1258 			    zhp->zfs_name, sdd->tosnap);
1259 		}
1260 		sdd->err = B_TRUE;
1261 	}
1262 
1263 	return (rv);
1264 }
1265 
1266 static int
1267 dump_filesystems(zfs_handle_t *rzhp, void *arg)
1268 {
1269 	send_dump_data_t *sdd = arg;
1270 	nvpair_t *fspair;
1271 	boolean_t needagain, progress;
1272 
1273 	if (!sdd->replicate)
1274 		return (dump_filesystem(rzhp, sdd));
1275 
1276 	/* Mark the clone origin snapshots. */
1277 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1278 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1279 		nvlist_t *nvfs;
1280 		uint64_t origin_guid = 0;
1281 
1282 		nvfs = fnvpair_value_nvlist(fspair);
1283 		(void) nvlist_lookup_uint64(nvfs, "origin", &origin_guid);
1284 		if (origin_guid != 0) {
1285 			char *snapname;
1286 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1287 			    origin_guid, &snapname);
1288 			if (origin_nv != NULL) {
1289 				nvlist_t *snapprops;
1290 				snapprops = fnvlist_lookup_nvlist(origin_nv,
1291 				    "snapprops");
1292 				snapprops = fnvlist_lookup_nvlist(snapprops,
1293 				    snapname);
1294 				fnvlist_add_boolean(snapprops,
1295 				    "is_clone_origin");
1296 			}
1297 		}
1298 	}
1299 again:
1300 	needagain = progress = B_FALSE;
1301 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1302 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1303 		nvlist_t *fslist, *parent_nv;
1304 		char *fsname;
1305 		zfs_handle_t *zhp;
1306 		int err;
1307 		uint64_t origin_guid = 0;
1308 		uint64_t parent_guid = 0;
1309 
1310 		fslist = fnvpair_value_nvlist(fspair);
1311 		if (nvlist_lookup_boolean(fslist, "sent") == 0)
1312 			continue;
1313 
1314 		fsname = fnvlist_lookup_string(fslist, "name");
1315 		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
1316 		(void) nvlist_lookup_uint64(fslist, "parentfromsnap",
1317 		    &parent_guid);
1318 
1319 		if (parent_guid != 0) {
1320 			parent_nv = fsavl_find(sdd->fsavl, parent_guid, NULL);
1321 			if (!nvlist_exists(parent_nv, "sent")) {
1322 				/* parent has not been sent; skip this one */
1323 				needagain = B_TRUE;
1324 				continue;
1325 			}
1326 		}
1327 
1328 		if (origin_guid != 0) {
1329 			nvlist_t *origin_nv = fsavl_find(sdd->fsavl,
1330 			    origin_guid, NULL);
1331 			if (origin_nv != NULL &&
1332 			    !nvlist_exists(origin_nv, "sent")) {
1333 				/*
1334 				 * origin has not been sent yet;
1335 				 * skip this clone.
1336 				 */
1337 				needagain = B_TRUE;
1338 				continue;
1339 			}
1340 		}
1341 
1342 		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
1343 		if (zhp == NULL)
1344 			return (-1);
1345 		err = dump_filesystem(zhp, sdd);
1346 		fnvlist_add_boolean(fslist, "sent");
1347 		progress = B_TRUE;
1348 		zfs_close(zhp);
1349 		if (err)
1350 			return (err);
1351 	}
1352 	if (needagain) {
1353 		assert(progress);
1354 		goto again;
1355 	}
1356 
1357 	/* clean out the sent flags in case we reuse this fss */
1358 	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
1359 	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
1360 		nvlist_t *fslist;
1361 
1362 		fslist = fnvpair_value_nvlist(fspair);
1363 		(void) nvlist_remove_all(fslist, "sent");
1364 	}
1365 
1366 	return (0);
1367 }
1368 
1369 nvlist_t *
1370 zfs_send_resume_token_to_nvlist(libzfs_handle_t *hdl, const char *token)
1371 {
1372 	unsigned int version;
1373 	int nread, i;
1374 	unsigned long long checksum, packed_len;
1375 
1376 	/*
1377 	 * Decode token header, which is:
1378 	 *   <token version>-<checksum of payload>-<uncompressed payload length>
1379 	 * Note that the only supported token version is 1.
1380 	 */
1381 	nread = sscanf(token, "%u-%llx-%llx-",
1382 	    &version, &checksum, &packed_len);
1383 	if (nread != 3) {
1384 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1385 		    "resume token is corrupt (invalid format)"));
1386 		return (NULL);
1387 	}
1388 
1389 	if (version != ZFS_SEND_RESUME_TOKEN_VERSION) {
1390 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1391 		    "resume token is corrupt (invalid version %u)"),
1392 		    version);
1393 		return (NULL);
1394 	}
1395 
1396 	/* convert hexadecimal representation to binary */
1397 	token = strrchr(token, '-') + 1;
1398 	int len = strlen(token) / 2;
1399 	unsigned char *compressed = zfs_alloc(hdl, len);
1400 	for (i = 0; i < len; i++) {
1401 		nread = sscanf(token + i * 2, "%2hhx", compressed + i);
1402 		if (nread != 1) {
1403 			free(compressed);
1404 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1405 			    "resume token is corrupt "
1406 			    "(payload is not hex-encoded)"));
1407 			return (NULL);
1408 		}
1409 	}
1410 
1411 	/* verify checksum */
1412 	zio_cksum_t cksum;
1413 	fletcher_4_native_varsize(compressed, len, &cksum);
1414 	if (cksum.zc_word[0] != checksum) {
1415 		free(compressed);
1416 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1417 		    "resume token is corrupt (incorrect checksum)"));
1418 		return (NULL);
1419 	}
1420 
1421 	/* uncompress */
1422 	void *packed = zfs_alloc(hdl, packed_len);
1423 	uLongf packed_len_long = packed_len;
1424 	if (uncompress(packed, &packed_len_long, compressed, len) != Z_OK ||
1425 	    packed_len_long != packed_len) {
1426 		free(packed);
1427 		free(compressed);
1428 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1429 		    "resume token is corrupt (decompression failed)"));
1430 		return (NULL);
1431 	}
1432 
1433 	/* unpack nvlist */
1434 	nvlist_t *nv;
1435 	int error = nvlist_unpack(packed, packed_len, &nv, KM_SLEEP);
1436 	free(packed);
1437 	free(compressed);
1438 	if (error != 0) {
1439 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1440 		    "resume token is corrupt (nvlist_unpack failed)"));
1441 		return (NULL);
1442 	}
1443 	return (nv);
1444 }
1445 static enum lzc_send_flags
1446 lzc_flags_from_sendflags(const sendflags_t *flags)
1447 {
1448 	enum lzc_send_flags lzc_flags = 0;
1449 	if (flags->largeblock)
1450 		lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1451 	if (flags->embed_data)
1452 		lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
1453 	if (flags->compress)
1454 		lzc_flags |= LZC_SEND_FLAG_COMPRESS;
1455 	if (flags->raw)
1456 		lzc_flags |= LZC_SEND_FLAG_RAW;
1457 	if (flags->saved)
1458 		lzc_flags |= LZC_SEND_FLAG_SAVED;
1459 	return (lzc_flags);
1460 }
1461 
1462 static int
1463 estimate_size(zfs_handle_t *zhp, const char *from, int fd, sendflags_t *flags,
1464     uint64_t resumeobj, uint64_t resumeoff, uint64_t bytes,
1465     const char *redactbook, char *errbuf)
1466 {
1467 	uint64_t size;
1468 	FILE *fout = flags->dryrun ? stdout : stderr;
1469 	progress_arg_t pa = { 0 };
1470 	int err = 0;
1471 	pthread_t ptid;
1472 
1473 	if (flags->progress) {
1474 		pa.pa_zhp = zhp;
1475 		pa.pa_fd = fd;
1476 		pa.pa_parsable = flags->parsable;
1477 		pa.pa_estimate = B_TRUE;
1478 		pa.pa_verbosity = flags->verbosity;
1479 
1480 		err = pthread_create(&ptid, NULL,
1481 		    send_progress_thread, &pa);
1482 		if (err != 0) {
1483 			zfs_error_aux(zhp->zfs_hdl, "%s", strerror(errno));
1484 			return (zfs_error(zhp->zfs_hdl,
1485 			    EZFS_THREADCREATEFAILED, errbuf));
1486 		}
1487 	}
1488 
1489 	err = lzc_send_space_resume_redacted(zhp->zfs_name, from,
1490 	    lzc_flags_from_sendflags(flags), resumeobj, resumeoff, bytes,
1491 	    redactbook, fd, &size);
1492 
1493 	if (flags->progress) {
1494 		void *status = NULL;
1495 		(void) pthread_cancel(ptid);
1496 		(void) pthread_join(ptid, &status);
1497 		int error = (int)(uintptr_t)status;
1498 		if (error != 0 && status != PTHREAD_CANCELED) {
1499 			char errbuf[1024];
1500 			(void) snprintf(errbuf, sizeof (errbuf),
1501 			    dgettext(TEXT_DOMAIN, "progress thread exited "
1502 			    "nonzero"));
1503 			return (zfs_standard_error(zhp->zfs_hdl, error,
1504 			    errbuf));
1505 		}
1506 	}
1507 
1508 	if (err != 0) {
1509 		zfs_error_aux(zhp->zfs_hdl, "%s", strerror(err));
1510 		return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
1511 		    errbuf));
1512 	}
1513 	send_print_verbose(fout, zhp->zfs_name, from, size,
1514 	    flags->parsable);
1515 
1516 	if (flags->parsable) {
1517 		(void) fprintf(fout, "size\t%llu\n", (longlong_t)size);
1518 	} else {
1519 		char buf[16];
1520 		zfs_nicenum(size, buf, sizeof (buf));
1521 		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1522 		    "total estimated size is %s\n"), buf);
1523 	}
1524 	return (0);
1525 }
1526 
1527 static boolean_t
1528 redact_snaps_contains(const uint64_t *snaps, uint64_t num_snaps, uint64_t guid)
1529 {
1530 	for (int i = 0; i < num_snaps; i++) {
1531 		if (snaps[i] == guid)
1532 			return (B_TRUE);
1533 	}
1534 	return (B_FALSE);
1535 }
1536 
1537 static boolean_t
1538 redact_snaps_equal(const uint64_t *snaps1, uint64_t num_snaps1,
1539     const uint64_t *snaps2, uint64_t num_snaps2)
1540 {
1541 	if (num_snaps1 != num_snaps2)
1542 		return (B_FALSE);
1543 	for (int i = 0; i < num_snaps1; i++) {
1544 		if (!redact_snaps_contains(snaps2, num_snaps2, snaps1[i]))
1545 			return (B_FALSE);
1546 	}
1547 	return (B_TRUE);
1548 }
1549 
1550 /*
1551  * Check that the list of redaction snapshots in the bookmark matches the send
1552  * we're resuming, and return whether or not it's complete.
1553  *
1554  * Note that the caller needs to free the contents of *bookname with free() if
1555  * this function returns successfully.
1556  */
1557 static int
1558 find_redact_book(libzfs_handle_t *hdl, const char *path,
1559     const uint64_t *redact_snap_guids, int num_redact_snaps,
1560     char **bookname)
1561 {
1562 	char errbuf[1024];
1563 	int error = 0;
1564 	nvlist_t *props = fnvlist_alloc();
1565 	nvlist_t *bmarks;
1566 
1567 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1568 	    "cannot resume send"));
1569 
1570 	fnvlist_add_boolean(props, "redact_complete");
1571 	fnvlist_add_boolean(props, zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS));
1572 	error = lzc_get_bookmarks(path, props, &bmarks);
1573 	fnvlist_free(props);
1574 	if (error != 0) {
1575 		if (error == ESRCH) {
1576 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1577 			    "nonexistent redaction bookmark provided"));
1578 		} else if (error == ENOENT) {
1579 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1580 			    "dataset to be sent no longer exists"));
1581 		} else {
1582 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1583 			    "unknown error: %s"), strerror(error));
1584 		}
1585 		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1586 	}
1587 	nvpair_t *pair;
1588 	for (pair = nvlist_next_nvpair(bmarks, NULL); pair;
1589 	    pair = nvlist_next_nvpair(bmarks, pair)) {
1590 
1591 		nvlist_t *bmark = fnvpair_value_nvlist(pair);
1592 		nvlist_t *vallist = fnvlist_lookup_nvlist(bmark,
1593 		    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS));
1594 		uint_t len = 0;
1595 		uint64_t *bmarksnaps = fnvlist_lookup_uint64_array(vallist,
1596 		    ZPROP_VALUE, &len);
1597 		if (redact_snaps_equal(redact_snap_guids,
1598 		    num_redact_snaps, bmarksnaps, len)) {
1599 			break;
1600 		}
1601 	}
1602 	if (pair == NULL)  {
1603 		fnvlist_free(bmarks);
1604 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1605 		    "no appropriate redaction bookmark exists"));
1606 		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1607 	}
1608 	char *name = nvpair_name(pair);
1609 	nvlist_t *bmark = fnvpair_value_nvlist(pair);
1610 	nvlist_t *vallist = fnvlist_lookup_nvlist(bmark, "redact_complete");
1611 	boolean_t complete = fnvlist_lookup_boolean_value(vallist,
1612 	    ZPROP_VALUE);
1613 	if (!complete) {
1614 		fnvlist_free(bmarks);
1615 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1616 		    "incomplete redaction bookmark provided"));
1617 		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
1618 	}
1619 	*bookname = strndup(name, ZFS_MAX_DATASET_NAME_LEN);
1620 	ASSERT3P(*bookname, !=, NULL);
1621 	fnvlist_free(bmarks);
1622 	return (0);
1623 }
1624 
1625 static int
1626 zfs_send_resume_impl(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
1627     nvlist_t *resume_nvl)
1628 {
1629 	char errbuf[1024];
1630 	char *toname;
1631 	char *fromname = NULL;
1632 	uint64_t resumeobj, resumeoff, toguid, fromguid, bytes;
1633 	zfs_handle_t *zhp;
1634 	int error = 0;
1635 	char name[ZFS_MAX_DATASET_NAME_LEN];
1636 	enum lzc_send_flags lzc_flags = 0;
1637 	FILE *fout = (flags->verbosity > 0 && flags->dryrun) ? stdout : stderr;
1638 	uint64_t *redact_snap_guids = NULL;
1639 	int num_redact_snaps = 0;
1640 	char *redact_book = NULL;
1641 
1642 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1643 	    "cannot resume send"));
1644 
1645 	if (flags->verbosity != 0) {
1646 		(void) fprintf(fout, dgettext(TEXT_DOMAIN,
1647 		    "resume token contents:\n"));
1648 		nvlist_print(fout, resume_nvl);
1649 	}
1650 
1651 	if (nvlist_lookup_string(resume_nvl, "toname", &toname) != 0 ||
1652 	    nvlist_lookup_uint64(resume_nvl, "object", &resumeobj) != 0 ||
1653 	    nvlist_lookup_uint64(resume_nvl, "offset", &resumeoff) != 0 ||
1654 	    nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
1655 	    nvlist_lookup_uint64(resume_nvl, "toguid", &toguid) != 0) {
1656 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1657 		    "resume token is corrupt"));
1658 		return (zfs_error(hdl, EZFS_FAULT, errbuf));
1659 	}
1660 	fromguid = 0;
1661 	(void) nvlist_lookup_uint64(resume_nvl, "fromguid", &fromguid);
1662 
1663 	if (flags->largeblock || nvlist_exists(resume_nvl, "largeblockok"))
1664 		lzc_flags |= LZC_SEND_FLAG_LARGE_BLOCK;
1665 	if (flags->embed_data || nvlist_exists(resume_nvl, "embedok"))
1666 		lzc_flags |= LZC_SEND_FLAG_EMBED_DATA;
1667 	if (flags->compress || nvlist_exists(resume_nvl, "compressok"))
1668 		lzc_flags |= LZC_SEND_FLAG_COMPRESS;
1669 	if (flags->raw || nvlist_exists(resume_nvl, "rawok"))
1670 		lzc_flags |= LZC_SEND_FLAG_RAW;
1671 	if (flags->saved || nvlist_exists(resume_nvl, "savedok"))
1672 		lzc_flags |= LZC_SEND_FLAG_SAVED;
1673 
1674 	if (flags->saved) {
1675 		(void) strcpy(name, toname);
1676 	} else {
1677 		error = guid_to_name(hdl, toname, toguid, B_FALSE, name);
1678 		if (error != 0) {
1679 			if (zfs_dataset_exists(hdl, toname, ZFS_TYPE_DATASET)) {
1680 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1681 				    "'%s' is no longer the same snapshot "
1682 				    "used in the initial send"), toname);
1683 			} else {
1684 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1685 				    "'%s' used in the initial send no "
1686 				    "longer exists"), toname);
1687 			}
1688 			return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1689 		}
1690 	}
1691 
1692 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
1693 	if (zhp == NULL) {
1694 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1695 		    "unable to access '%s'"), name);
1696 		return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1697 	}
1698 
1699 	if (nvlist_lookup_uint64_array(resume_nvl, "book_redact_snaps",
1700 	    &redact_snap_guids, (uint_t *)&num_redact_snaps) != 0) {
1701 		num_redact_snaps = -1;
1702 	}
1703 
1704 	if (fromguid != 0) {
1705 		if (guid_to_name_redact_snaps(hdl, toname, fromguid, B_TRUE,
1706 		    redact_snap_guids, num_redact_snaps, name) != 0) {
1707 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1708 			    "incremental source %#llx no longer exists"),
1709 			    (longlong_t)fromguid);
1710 			return (zfs_error(hdl, EZFS_BADPATH, errbuf));
1711 		}
1712 		fromname = name;
1713 	}
1714 
1715 	redact_snap_guids = NULL;
1716 
1717 	if (nvlist_lookup_uint64_array(resume_nvl,
1718 	    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS), &redact_snap_guids,
1719 	    (uint_t *)&num_redact_snaps) == 0) {
1720 		char path[ZFS_MAX_DATASET_NAME_LEN];
1721 
1722 		(void) strlcpy(path, toname, sizeof (path));
1723 		char *at = strchr(path, '@');
1724 		ASSERT3P(at, !=, NULL);
1725 
1726 		*at = '\0';
1727 
1728 		if ((error = find_redact_book(hdl, path, redact_snap_guids,
1729 		    num_redact_snaps, &redact_book)) != 0) {
1730 			return (error);
1731 		}
1732 	}
1733 
1734 	if (flags->verbosity != 0) {
1735 		/*
1736 		 * Some of these may have come from the resume token, set them
1737 		 * here for size estimate purposes.
1738 		 */
1739 		sendflags_t tmpflags = *flags;
1740 		if (lzc_flags & LZC_SEND_FLAG_LARGE_BLOCK)
1741 			tmpflags.largeblock = B_TRUE;
1742 		if (lzc_flags & LZC_SEND_FLAG_COMPRESS)
1743 			tmpflags.compress = B_TRUE;
1744 		if (lzc_flags & LZC_SEND_FLAG_EMBED_DATA)
1745 			tmpflags.embed_data = B_TRUE;
1746 		error = estimate_size(zhp, fromname, outfd, &tmpflags,
1747 		    resumeobj, resumeoff, bytes, redact_book, errbuf);
1748 	}
1749 
1750 	if (!flags->dryrun) {
1751 		progress_arg_t pa = { 0 };
1752 		pthread_t tid;
1753 		/*
1754 		 * If progress reporting is requested, spawn a new thread to
1755 		 * poll ZFS_IOC_SEND_PROGRESS at a regular interval.
1756 		 */
1757 		if (flags->progress) {
1758 			pa.pa_zhp = zhp;
1759 			pa.pa_fd = outfd;
1760 			pa.pa_parsable = flags->parsable;
1761 			pa.pa_estimate = B_FALSE;
1762 			pa.pa_verbosity = flags->verbosity;
1763 
1764 			error = pthread_create(&tid, NULL,
1765 			    send_progress_thread, &pa);
1766 			if (error != 0) {
1767 				if (redact_book != NULL)
1768 					free(redact_book);
1769 				zfs_close(zhp);
1770 				return (error);
1771 			}
1772 		}
1773 
1774 		error = lzc_send_resume_redacted(zhp->zfs_name, fromname, outfd,
1775 		    lzc_flags, resumeobj, resumeoff, redact_book);
1776 		if (redact_book != NULL)
1777 			free(redact_book);
1778 
1779 		if (flags->progress) {
1780 			void *status = NULL;
1781 			(void) pthread_cancel(tid);
1782 			(void) pthread_join(tid, &status);
1783 			int error = (int)(uintptr_t)status;
1784 			if (error != 0 && status != PTHREAD_CANCELED) {
1785 				char errbuf[1024];
1786 				(void) snprintf(errbuf, sizeof (errbuf),
1787 				    dgettext(TEXT_DOMAIN,
1788 				    "progress thread exited nonzero"));
1789 				return (zfs_standard_error(hdl, error, errbuf));
1790 			}
1791 		}
1792 
1793 		char errbuf[1024];
1794 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1795 		    "warning: cannot send '%s'"), zhp->zfs_name);
1796 
1797 		zfs_close(zhp);
1798 
1799 		switch (error) {
1800 		case 0:
1801 			return (0);
1802 		case EACCES:
1803 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1804 			    "source key must be loaded"));
1805 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
1806 		case ESRCH:
1807 			if (lzc_exists(zhp->zfs_name)) {
1808 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1809 				    "incremental source could not be found"));
1810 			}
1811 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1812 
1813 		case EXDEV:
1814 		case ENOENT:
1815 		case EDQUOT:
1816 		case EFBIG:
1817 		case EIO:
1818 		case ENOLINK:
1819 		case ENOSPC:
1820 		case ENOSTR:
1821 		case ENXIO:
1822 		case EPIPE:
1823 		case ERANGE:
1824 		case EFAULT:
1825 		case EROFS:
1826 			zfs_error_aux(hdl, "%s", strerror(errno));
1827 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
1828 
1829 		default:
1830 			return (zfs_standard_error(hdl, errno, errbuf));
1831 		}
1832 	} else {
1833 		if (redact_book != NULL)
1834 			free(redact_book);
1835 	}
1836 
1837 	zfs_close(zhp);
1838 
1839 	return (error);
1840 }
1841 
1842 int
1843 zfs_send_resume(libzfs_handle_t *hdl, sendflags_t *flags, int outfd,
1844     const char *resume_token)
1845 {
1846 	int ret;
1847 	char errbuf[1024];
1848 	nvlist_t *resume_nvl;
1849 
1850 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1851 	    "cannot resume send"));
1852 
1853 	resume_nvl = zfs_send_resume_token_to_nvlist(hdl, resume_token);
1854 	if (resume_nvl == NULL) {
1855 		/*
1856 		 * zfs_error_aux has already been set by
1857 		 * zfs_send_resume_token_to_nvlist()
1858 		 */
1859 		return (zfs_error(hdl, EZFS_FAULT, errbuf));
1860 	}
1861 
1862 	ret = zfs_send_resume_impl(hdl, flags, outfd, resume_nvl);
1863 	fnvlist_free(resume_nvl);
1864 
1865 	return (ret);
1866 }
1867 
1868 int
1869 zfs_send_saved(zfs_handle_t *zhp, sendflags_t *flags, int outfd,
1870     const char *resume_token)
1871 {
1872 	int ret;
1873 	libzfs_handle_t *hdl = zhp->zfs_hdl;
1874 	nvlist_t *saved_nvl = NULL, *resume_nvl = NULL;
1875 	uint64_t saved_guid = 0, resume_guid = 0;
1876 	uint64_t obj = 0, off = 0, bytes = 0;
1877 	char token_buf[ZFS_MAXPROPLEN];
1878 	char errbuf[1024];
1879 
1880 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1881 	    "saved send failed"));
1882 
1883 	ret = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
1884 	    token_buf, sizeof (token_buf), NULL, NULL, 0, B_TRUE);
1885 	if (ret != 0)
1886 		goto out;
1887 
1888 	saved_nvl = zfs_send_resume_token_to_nvlist(hdl, token_buf);
1889 	if (saved_nvl == NULL) {
1890 		/*
1891 		 * zfs_error_aux has already been set by
1892 		 * zfs_send_resume_token_to_nvlist()
1893 		 */
1894 		ret = zfs_error(hdl, EZFS_FAULT, errbuf);
1895 		goto out;
1896 	}
1897 
1898 	/*
1899 	 * If a resume token is provided we use the object and offset
1900 	 * from that instead of the default, which starts from the
1901 	 * beginning.
1902 	 */
1903 	if (resume_token != NULL) {
1904 		resume_nvl = zfs_send_resume_token_to_nvlist(hdl,
1905 		    resume_token);
1906 		if (resume_nvl == NULL) {
1907 			ret = zfs_error(hdl, EZFS_FAULT, errbuf);
1908 			goto out;
1909 		}
1910 
1911 		if (nvlist_lookup_uint64(resume_nvl, "object", &obj) != 0 ||
1912 		    nvlist_lookup_uint64(resume_nvl, "offset", &off) != 0 ||
1913 		    nvlist_lookup_uint64(resume_nvl, "bytes", &bytes) != 0 ||
1914 		    nvlist_lookup_uint64(resume_nvl, "toguid",
1915 		    &resume_guid) != 0) {
1916 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1917 			    "provided resume token is corrupt"));
1918 			ret = zfs_error(hdl, EZFS_FAULT, errbuf);
1919 			goto out;
1920 		}
1921 
1922 		if (nvlist_lookup_uint64(saved_nvl, "toguid",
1923 		    &saved_guid)) {
1924 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1925 			    "dataset's resume token is corrupt"));
1926 			ret = zfs_error(hdl, EZFS_FAULT, errbuf);
1927 			goto out;
1928 		}
1929 
1930 		if (resume_guid != saved_guid) {
1931 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1932 			    "provided resume token does not match dataset"));
1933 			ret = zfs_error(hdl, EZFS_BADBACKUP, errbuf);
1934 			goto out;
1935 		}
1936 	}
1937 
1938 	(void) nvlist_remove_all(saved_nvl, "object");
1939 	fnvlist_add_uint64(saved_nvl, "object", obj);
1940 
1941 	(void) nvlist_remove_all(saved_nvl, "offset");
1942 	fnvlist_add_uint64(saved_nvl, "offset", off);
1943 
1944 	(void) nvlist_remove_all(saved_nvl, "bytes");
1945 	fnvlist_add_uint64(saved_nvl, "bytes", bytes);
1946 
1947 	(void) nvlist_remove_all(saved_nvl, "toname");
1948 	fnvlist_add_string(saved_nvl, "toname", zhp->zfs_name);
1949 
1950 	ret = zfs_send_resume_impl(hdl, flags, outfd, saved_nvl);
1951 
1952 out:
1953 	fnvlist_free(saved_nvl);
1954 	fnvlist_free(resume_nvl);
1955 	return (ret);
1956 }
1957 
1958 /*
1959  * This function informs the target system that the recursive send is complete.
1960  * The record is also expected in the case of a send -p.
1961  */
1962 static int
1963 send_conclusion_record(int fd, zio_cksum_t *zc)
1964 {
1965 	dmu_replay_record_t drr = { 0 };
1966 	drr.drr_type = DRR_END;
1967 	if (zc != NULL)
1968 		drr.drr_u.drr_end.drr_checksum = *zc;
1969 	if (write(fd, &drr, sizeof (drr)) == -1) {
1970 		return (errno);
1971 	}
1972 	return (0);
1973 }
1974 
1975 /*
1976  * This function is responsible for sending the records that contain the
1977  * necessary information for the target system's libzfs to be able to set the
1978  * properties of the filesystem being received, or to be able to prepare for
1979  * a recursive receive.
1980  *
1981  * The "zhp" argument is the handle of the snapshot we are sending
1982  * (the "tosnap").  The "from" argument is the short snapshot name (the part
1983  * after the @) of the incremental source.
1984  */
1985 static int
1986 send_prelim_records(zfs_handle_t *zhp, const char *from, int fd,
1987     boolean_t gather_props, boolean_t recursive, boolean_t verbose,
1988     boolean_t dryrun, boolean_t raw, boolean_t replicate, boolean_t skipmissing,
1989     boolean_t backup, boolean_t holds, boolean_t props, boolean_t doall,
1990     nvlist_t **fssp, avl_tree_t **fsavlp)
1991 {
1992 	int err = 0;
1993 	char *packbuf = NULL;
1994 	size_t buflen = 0;
1995 	zio_cksum_t zc = { {0} };
1996 	int featureflags = 0;
1997 	/* name of filesystem/volume that contains snapshot we are sending */
1998 	char tofs[ZFS_MAX_DATASET_NAME_LEN];
1999 	/* short name of snap we are sending */
2000 	char *tosnap = "";
2001 
2002 	char errbuf[1024];
2003 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2004 	    "warning: cannot send '%s'"), zhp->zfs_name);
2005 	if (zhp->zfs_type == ZFS_TYPE_FILESYSTEM && zfs_prop_get_int(zhp,
2006 	    ZFS_PROP_VERSION) >= ZPL_VERSION_SA) {
2007 		featureflags |= DMU_BACKUP_FEATURE_SA_SPILL;
2008 	}
2009 
2010 	if (holds)
2011 		featureflags |= DMU_BACKUP_FEATURE_HOLDS;
2012 
2013 	(void) strlcpy(tofs, zhp->zfs_name, ZFS_MAX_DATASET_NAME_LEN);
2014 	char *at = strchr(tofs, '@');
2015 	if (at != NULL) {
2016 		*at = '\0';
2017 		tosnap = at + 1;
2018 	}
2019 
2020 	if (gather_props) {
2021 		nvlist_t *hdrnv = fnvlist_alloc();
2022 		nvlist_t *fss = NULL;
2023 
2024 		if (from != NULL)
2025 			fnvlist_add_string(hdrnv, "fromsnap", from);
2026 		fnvlist_add_string(hdrnv, "tosnap", tosnap);
2027 		if (!recursive)
2028 			fnvlist_add_boolean(hdrnv, "not_recursive");
2029 
2030 		if (raw) {
2031 			fnvlist_add_boolean(hdrnv, "raw");
2032 		}
2033 
2034 		if ((err = gather_nvlist(zhp->zfs_hdl, tofs,
2035 		    from, tosnap, recursive, raw, doall, replicate, skipmissing,
2036 		    verbose, backup, holds, props, &fss, fsavlp)) != 0) {
2037 			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
2038 			    errbuf));
2039 		}
2040 		/*
2041 		 * Do not allow the size of the properties list to exceed
2042 		 * the limit
2043 		 */
2044 		if ((fnvlist_size(fss) + fnvlist_size(hdrnv)) >
2045 		    zhp->zfs_hdl->libzfs_max_nvlist) {
2046 			(void) snprintf(errbuf, sizeof (errbuf),
2047 			    dgettext(TEXT_DOMAIN, "warning: cannot send '%s': "
2048 			    "the size of the list of snapshots and properties "
2049 			    "is too large to be received successfully.\n"
2050 			    "Select a smaller number of snapshots to send.\n"),
2051 			    zhp->zfs_name);
2052 			return (zfs_error(zhp->zfs_hdl, EZFS_NOSPC,
2053 			    errbuf));
2054 		}
2055 		fnvlist_add_nvlist(hdrnv, "fss", fss);
2056 		VERIFY0(nvlist_pack(hdrnv, &packbuf, &buflen, NV_ENCODE_XDR,
2057 		    0));
2058 		if (fssp != NULL) {
2059 			*fssp = fss;
2060 		} else {
2061 			fnvlist_free(fss);
2062 		}
2063 		fnvlist_free(hdrnv);
2064 	}
2065 
2066 	if (!dryrun) {
2067 		dmu_replay_record_t drr = { 0 };
2068 		/* write first begin record */
2069 		drr.drr_type = DRR_BEGIN;
2070 		drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
2071 		DMU_SET_STREAM_HDRTYPE(drr.drr_u.drr_begin.
2072 		    drr_versioninfo, DMU_COMPOUNDSTREAM);
2073 		DMU_SET_FEATUREFLAGS(drr.drr_u.drr_begin.
2074 		    drr_versioninfo, featureflags);
2075 		if (snprintf(drr.drr_u.drr_begin.drr_toname,
2076 		    sizeof (drr.drr_u.drr_begin.drr_toname), "%s@%s", tofs,
2077 		    tosnap) >= sizeof (drr.drr_u.drr_begin.drr_toname)) {
2078 			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
2079 			    errbuf));
2080 		}
2081 		drr.drr_payloadlen = buflen;
2082 
2083 		err = dump_record(&drr, packbuf, buflen, &zc, fd);
2084 		free(packbuf);
2085 		if (err != 0) {
2086 			zfs_error_aux(zhp->zfs_hdl, "%s", strerror(err));
2087 			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
2088 			    errbuf));
2089 		}
2090 		err = send_conclusion_record(fd, &zc);
2091 		if (err != 0) {
2092 			zfs_error_aux(zhp->zfs_hdl, "%s", strerror(err));
2093 			return (zfs_error(zhp->zfs_hdl, EZFS_BADBACKUP,
2094 			    errbuf));
2095 		}
2096 	}
2097 	return (0);
2098 }
2099 
2100 /*
2101  * Generate a send stream.  The "zhp" argument is the filesystem/volume
2102  * that contains the snapshot to send.  The "fromsnap" argument is the
2103  * short name (the part after the '@') of the snapshot that is the
2104  * incremental source to send from (if non-NULL).  The "tosnap" argument
2105  * is the short name of the snapshot to send.
2106  *
2107  * The content of the send stream is the snapshot identified by
2108  * 'tosnap'.  Incremental streams are requested in two ways:
2109  *     - from the snapshot identified by "fromsnap" (if non-null) or
2110  *     - from the origin of the dataset identified by zhp, which must
2111  *	 be a clone.  In this case, "fromsnap" is null and "fromorigin"
2112  *	 is TRUE.
2113  *
2114  * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
2115  * uses a special header (with a hdrtype field of DMU_COMPOUNDSTREAM)
2116  * if "replicate" is set.  If "doall" is set, dump all the intermediate
2117  * snapshots. The DMU_COMPOUNDSTREAM header is used in the "doall"
2118  * case too. If "props" is set, send properties.
2119  */
2120 int
2121 zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
2122     sendflags_t *flags, int outfd, snapfilter_cb_t filter_func,
2123     void *cb_arg, nvlist_t **debugnvp)
2124 {
2125 	char errbuf[1024];
2126 	send_dump_data_t sdd = { 0 };
2127 	int err = 0;
2128 	nvlist_t *fss = NULL;
2129 	avl_tree_t *fsavl = NULL;
2130 	static uint64_t holdseq;
2131 	int spa_version;
2132 	FILE *fout;
2133 
2134 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2135 	    "cannot send '%s'"), zhp->zfs_name);
2136 
2137 	if (fromsnap && fromsnap[0] == '\0') {
2138 		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
2139 		    "zero-length incremental source"));
2140 		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
2141 	}
2142 
2143 	if (flags->replicate || flags->doall || flags->props ||
2144 	    flags->holds || flags->backup) {
2145 		char full_tosnap_name[ZFS_MAX_DATASET_NAME_LEN];
2146 		if (snprintf(full_tosnap_name, sizeof (full_tosnap_name),
2147 		    "%s@%s", zhp->zfs_name, tosnap) >=
2148 		    sizeof (full_tosnap_name)) {
2149 			err = EINVAL;
2150 			goto stderr_out;
2151 		}
2152 		zfs_handle_t *tosnap = zfs_open(zhp->zfs_hdl,
2153 		    full_tosnap_name, ZFS_TYPE_SNAPSHOT);
2154 		if (tosnap == NULL) {
2155 			err = -1;
2156 			goto err_out;
2157 		}
2158 		err = send_prelim_records(tosnap, fromsnap, outfd,
2159 		    flags->replicate || flags->props || flags->holds,
2160 		    flags->replicate, flags->verbosity > 0, flags->dryrun,
2161 		    flags->raw, flags->replicate, flags->skipmissing,
2162 		    flags->backup, flags->holds, flags->props, flags->doall,
2163 		    &fss, &fsavl);
2164 		zfs_close(tosnap);
2165 		if (err != 0)
2166 			goto err_out;
2167 	}
2168 
2169 	/* dump each stream */
2170 	sdd.fromsnap = fromsnap;
2171 	sdd.tosnap = tosnap;
2172 	sdd.outfd = outfd;
2173 	sdd.replicate = flags->replicate;
2174 	sdd.doall = flags->doall;
2175 	sdd.fromorigin = flags->fromorigin;
2176 	sdd.fss = fss;
2177 	sdd.fsavl = fsavl;
2178 	sdd.verbosity = flags->verbosity;
2179 	sdd.parsable = flags->parsable;
2180 	sdd.progress = flags->progress;
2181 	sdd.dryrun = flags->dryrun;
2182 	sdd.large_block = flags->largeblock;
2183 	sdd.embed_data = flags->embed_data;
2184 	sdd.compress = flags->compress;
2185 	sdd.raw = flags->raw;
2186 	sdd.holds = flags->holds;
2187 	sdd.filter_cb = filter_func;
2188 	sdd.filter_cb_arg = cb_arg;
2189 	if (debugnvp)
2190 		sdd.debugnv = *debugnvp;
2191 	if (sdd.verbosity != 0 && sdd.dryrun)
2192 		sdd.std_out = B_TRUE;
2193 	fout = sdd.std_out ? stdout : stderr;
2194 
2195 	/*
2196 	 * Some flags require that we place user holds on the datasets that are
2197 	 * being sent so they don't get destroyed during the send. We can skip
2198 	 * this step if the pool is imported read-only since the datasets cannot
2199 	 * be destroyed.
2200 	 */
2201 	if (!flags->dryrun && !zpool_get_prop_int(zfs_get_pool_handle(zhp),
2202 	    ZPOOL_PROP_READONLY, NULL) &&
2203 	    zfs_spa_version(zhp, &spa_version) == 0 &&
2204 	    spa_version >= SPA_VERSION_USERREFS &&
2205 	    (flags->doall || flags->replicate)) {
2206 		++holdseq;
2207 		(void) snprintf(sdd.holdtag, sizeof (sdd.holdtag),
2208 		    ".send-%d-%llu", getpid(), (u_longlong_t)holdseq);
2209 		sdd.cleanup_fd = open(ZFS_DEV, O_RDWR | O_CLOEXEC);
2210 		if (sdd.cleanup_fd < 0) {
2211 			err = errno;
2212 			goto stderr_out;
2213 		}
2214 		sdd.snapholds = fnvlist_alloc();
2215 	} else {
2216 		sdd.cleanup_fd = -1;
2217 		sdd.snapholds = NULL;
2218 	}
2219 
2220 	if (flags->verbosity != 0 || sdd.snapholds != NULL) {
2221 		/*
2222 		 * Do a verbose no-op dry run to get all the verbose output
2223 		 * or to gather snapshot hold's before generating any data,
2224 		 * then do a non-verbose real run to generate the streams.
2225 		 */
2226 		sdd.dryrun = B_TRUE;
2227 		err = dump_filesystems(zhp, &sdd);
2228 
2229 		if (err != 0)
2230 			goto stderr_out;
2231 
2232 		if (flags->verbosity != 0) {
2233 			if (flags->parsable) {
2234 				(void) fprintf(fout, "size\t%llu\n",
2235 				    (longlong_t)sdd.size);
2236 			} else {
2237 				char buf[16];
2238 				zfs_nicebytes(sdd.size, buf, sizeof (buf));
2239 				(void) fprintf(fout, dgettext(TEXT_DOMAIN,
2240 				    "total estimated size is %s\n"), buf);
2241 			}
2242 		}
2243 
2244 		/* Ensure no snaps found is treated as an error. */
2245 		if (!sdd.seento) {
2246 			err = ENOENT;
2247 			goto err_out;
2248 		}
2249 
2250 		/* Skip the second run if dryrun was requested. */
2251 		if (flags->dryrun)
2252 			goto err_out;
2253 
2254 		if (sdd.snapholds != NULL) {
2255 			err = zfs_hold_nvl(zhp, sdd.cleanup_fd, sdd.snapholds);
2256 			if (err != 0)
2257 				goto stderr_out;
2258 
2259 			fnvlist_free(sdd.snapholds);
2260 			sdd.snapholds = NULL;
2261 		}
2262 
2263 		sdd.dryrun = B_FALSE;
2264 		sdd.verbosity = 0;
2265 	}
2266 
2267 	err = dump_filesystems(zhp, &sdd);
2268 	fsavl_destroy(fsavl);
2269 	fnvlist_free(fss);
2270 
2271 	/* Ensure no snaps found is treated as an error. */
2272 	if (err == 0 && !sdd.seento)
2273 		err = ENOENT;
2274 
2275 	if (sdd.cleanup_fd != -1) {
2276 		VERIFY(0 == close(sdd.cleanup_fd));
2277 		sdd.cleanup_fd = -1;
2278 	}
2279 
2280 	if (!flags->dryrun && (flags->replicate || flags->doall ||
2281 	    flags->props || flags->backup || flags->holds)) {
2282 		/*
2283 		 * write final end record.  NB: want to do this even if
2284 		 * there was some error, because it might not be totally
2285 		 * failed.
2286 		 */
2287 		err = send_conclusion_record(outfd, NULL);
2288 		if (err != 0)
2289 			return (zfs_standard_error(zhp->zfs_hdl, err, errbuf));
2290 	}
2291 
2292 	return (err || sdd.err);
2293 
2294 stderr_out:
2295 	err = zfs_standard_error(zhp->zfs_hdl, err, errbuf);
2296 err_out:
2297 	fsavl_destroy(fsavl);
2298 	fnvlist_free(fss);
2299 	fnvlist_free(sdd.snapholds);
2300 
2301 	if (sdd.cleanup_fd != -1)
2302 		VERIFY(0 == close(sdd.cleanup_fd));
2303 	return (err);
2304 }
2305 
2306 static zfs_handle_t *
2307 name_to_dir_handle(libzfs_handle_t *hdl, const char *snapname)
2308 {
2309 	char dirname[ZFS_MAX_DATASET_NAME_LEN];
2310 	(void) strlcpy(dirname, snapname, ZFS_MAX_DATASET_NAME_LEN);
2311 	char *c = strchr(dirname, '@');
2312 	if (c != NULL)
2313 		*c = '\0';
2314 	return (zfs_open(hdl, dirname, ZFS_TYPE_DATASET));
2315 }
2316 
2317 /*
2318  * Returns B_TRUE if earlier is an earlier snapshot in later's timeline; either
2319  * an earlier snapshot in the same filesystem, or a snapshot before later's
2320  * origin, or it's origin's origin, etc.
2321  */
2322 static boolean_t
2323 snapshot_is_before(zfs_handle_t *earlier, zfs_handle_t *later)
2324 {
2325 	boolean_t ret;
2326 	uint64_t later_txg =
2327 	    (later->zfs_type == ZFS_TYPE_FILESYSTEM ||
2328 	    later->zfs_type == ZFS_TYPE_VOLUME ?
2329 	    UINT64_MAX : zfs_prop_get_int(later, ZFS_PROP_CREATETXG));
2330 	uint64_t earlier_txg = zfs_prop_get_int(earlier, ZFS_PROP_CREATETXG);
2331 
2332 	if (earlier_txg >= later_txg)
2333 		return (B_FALSE);
2334 
2335 	zfs_handle_t *earlier_dir = name_to_dir_handle(earlier->zfs_hdl,
2336 	    earlier->zfs_name);
2337 	zfs_handle_t *later_dir = name_to_dir_handle(later->zfs_hdl,
2338 	    later->zfs_name);
2339 
2340 	if (strcmp(earlier_dir->zfs_name, later_dir->zfs_name) == 0) {
2341 		zfs_close(earlier_dir);
2342 		zfs_close(later_dir);
2343 		return (B_TRUE);
2344 	}
2345 
2346 	char clonename[ZFS_MAX_DATASET_NAME_LEN];
2347 	if (zfs_prop_get(later_dir, ZFS_PROP_ORIGIN, clonename,
2348 	    ZFS_MAX_DATASET_NAME_LEN, NULL, NULL, 0, B_TRUE) != 0) {
2349 		zfs_close(earlier_dir);
2350 		zfs_close(later_dir);
2351 		return (B_FALSE);
2352 	}
2353 
2354 	zfs_handle_t *origin = zfs_open(earlier->zfs_hdl, clonename,
2355 	    ZFS_TYPE_DATASET);
2356 	uint64_t origin_txg = zfs_prop_get_int(origin, ZFS_PROP_CREATETXG);
2357 
2358 	/*
2359 	 * If "earlier" is exactly the origin, then
2360 	 * snapshot_is_before(earlier, origin) will return false (because
2361 	 * they're the same).
2362 	 */
2363 	if (origin_txg == earlier_txg &&
2364 	    strcmp(origin->zfs_name, earlier->zfs_name) == 0) {
2365 		zfs_close(earlier_dir);
2366 		zfs_close(later_dir);
2367 		zfs_close(origin);
2368 		return (B_TRUE);
2369 	}
2370 	zfs_close(earlier_dir);
2371 	zfs_close(later_dir);
2372 
2373 	ret = snapshot_is_before(earlier, origin);
2374 	zfs_close(origin);
2375 	return (ret);
2376 }
2377 
2378 /*
2379  * The "zhp" argument is the handle of the dataset to send (typically a
2380  * snapshot).  The "from" argument is the full name of the snapshot or
2381  * bookmark that is the incremental source.
2382  */
2383 int
2384 zfs_send_one(zfs_handle_t *zhp, const char *from, int fd, sendflags_t *flags,
2385     const char *redactbook)
2386 {
2387 	int err;
2388 	libzfs_handle_t *hdl = zhp->zfs_hdl;
2389 	char *name = zhp->zfs_name;
2390 	int orig_fd = fd;
2391 	pthread_t ptid;
2392 	progress_arg_t pa = { 0 };
2393 
2394 	char errbuf[1024];
2395 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2396 	    "warning: cannot send '%s'"), name);
2397 
2398 	if (from != NULL && strchr(from, '@')) {
2399 		zfs_handle_t *from_zhp = zfs_open(hdl, from,
2400 		    ZFS_TYPE_DATASET);
2401 		if (from_zhp == NULL)
2402 			return (-1);
2403 		if (!snapshot_is_before(from_zhp, zhp)) {
2404 			zfs_close(from_zhp);
2405 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2406 			    "not an earlier snapshot from the same fs"));
2407 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
2408 		}
2409 		zfs_close(from_zhp);
2410 	}
2411 
2412 	if (redactbook != NULL) {
2413 		char bookname[ZFS_MAX_DATASET_NAME_LEN];
2414 		nvlist_t *redact_snaps;
2415 		zfs_handle_t *book_zhp;
2416 		char *at, *pound;
2417 		int dsnamelen;
2418 
2419 		pound = strchr(redactbook, '#');
2420 		if (pound != NULL)
2421 			redactbook = pound + 1;
2422 		at = strchr(name, '@');
2423 		if (at == NULL) {
2424 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2425 			    "cannot do a redacted send to a filesystem"));
2426 			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2427 		}
2428 		dsnamelen = at - name;
2429 		if (snprintf(bookname, sizeof (bookname), "%.*s#%s",
2430 		    dsnamelen, name, redactbook)
2431 		    >= sizeof (bookname)) {
2432 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2433 			    "invalid bookmark name"));
2434 			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
2435 		}
2436 		book_zhp = zfs_open(hdl, bookname, ZFS_TYPE_BOOKMARK);
2437 		if (book_zhp == NULL)
2438 			return (-1);
2439 		if (nvlist_lookup_nvlist(book_zhp->zfs_props,
2440 		    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS),
2441 		    &redact_snaps) != 0 || redact_snaps == NULL) {
2442 			zfs_close(book_zhp);
2443 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2444 			    "not a redaction bookmark"));
2445 			return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
2446 		}
2447 		zfs_close(book_zhp);
2448 	}
2449 
2450 	/*
2451 	 * Send fs properties
2452 	 */
2453 	if (flags->props || flags->holds || flags->backup) {
2454 		/*
2455 		 * Note: the header generated by send_prelim_records()
2456 		 * assumes that the incremental source is in the same
2457 		 * filesystem/volume as the target (which is a requirement
2458 		 * when doing "zfs send -R").  But that isn't always the
2459 		 * case here (e.g. send from snap in origin, or send from
2460 		 * bookmark).  We pass from=NULL, which will omit this
2461 		 * information from the prelim records; it isn't used
2462 		 * when receiving this type of stream.
2463 		 */
2464 		err = send_prelim_records(zhp, NULL, fd, B_TRUE, B_FALSE,
2465 		    flags->verbosity > 0, flags->dryrun, flags->raw,
2466 		    flags->replicate, B_FALSE, flags->backup, flags->holds,
2467 		    flags->props, flags->doall, NULL, NULL);
2468 		if (err != 0)
2469 			return (err);
2470 	}
2471 
2472 	/*
2473 	 * Perform size estimate if verbose was specified.
2474 	 */
2475 	if (flags->verbosity != 0) {
2476 		err = estimate_size(zhp, from, fd, flags, 0, 0, 0, redactbook,
2477 		    errbuf);
2478 		if (err != 0)
2479 			return (err);
2480 	}
2481 
2482 	if (flags->dryrun)
2483 		return (0);
2484 
2485 	/*
2486 	 * If progress reporting is requested, spawn a new thread to poll
2487 	 * ZFS_IOC_SEND_PROGRESS at a regular interval.
2488 	 */
2489 	if (flags->progress) {
2490 		pa.pa_zhp = zhp;
2491 		pa.pa_fd = fd;
2492 		pa.pa_parsable = flags->parsable;
2493 		pa.pa_estimate = B_FALSE;
2494 		pa.pa_verbosity = flags->verbosity;
2495 
2496 		err = pthread_create(&ptid, NULL,
2497 		    send_progress_thread, &pa);
2498 		if (err != 0) {
2499 			zfs_error_aux(zhp->zfs_hdl, "%s", strerror(errno));
2500 			return (zfs_error(zhp->zfs_hdl,
2501 			    EZFS_THREADCREATEFAILED, errbuf));
2502 		}
2503 	}
2504 
2505 	err = lzc_send_redacted(name, from, fd,
2506 	    lzc_flags_from_sendflags(flags), redactbook);
2507 
2508 	if (flags->progress) {
2509 		void *status = NULL;
2510 		if (err != 0)
2511 			(void) pthread_cancel(ptid);
2512 		(void) pthread_join(ptid, &status);
2513 		int error = (int)(uintptr_t)status;
2514 		if (error != 0 && status != PTHREAD_CANCELED)
2515 			return (zfs_standard_error_fmt(hdl, error,
2516 			    dgettext(TEXT_DOMAIN,
2517 			    "progress thread exited nonzero")));
2518 	}
2519 
2520 	if (flags->props || flags->holds || flags->backup) {
2521 		/* Write the final end record. */
2522 		err = send_conclusion_record(orig_fd, NULL);
2523 		if (err != 0)
2524 			return (zfs_standard_error(hdl, err, errbuf));
2525 	}
2526 	if (err != 0) {
2527 		switch (errno) {
2528 		case EXDEV:
2529 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2530 			    "not an earlier snapshot from the same fs"));
2531 			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
2532 
2533 		case ENOENT:
2534 		case ESRCH:
2535 			if (lzc_exists(name)) {
2536 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2537 				    "incremental source (%s) does not exist"),
2538 				    from);
2539 			}
2540 			return (zfs_error(hdl, EZFS_NOENT, errbuf));
2541 
2542 		case EACCES:
2543 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2544 			    "dataset key must be loaded"));
2545 			return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
2546 
2547 		case EBUSY:
2548 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2549 			    "target is busy; if a filesystem, "
2550 			    "it must not be mounted"));
2551 			return (zfs_error(hdl, EZFS_BUSY, errbuf));
2552 
2553 		case EDQUOT:
2554 		case EFAULT:
2555 		case EFBIG:
2556 		case EINVAL:
2557 		case EIO:
2558 		case ENOLINK:
2559 		case ENOSPC:
2560 		case ENOSTR:
2561 		case ENXIO:
2562 		case EPIPE:
2563 		case ERANGE:
2564 		case EROFS:
2565 			zfs_error_aux(hdl, "%s", strerror(errno));
2566 			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
2567 
2568 		default:
2569 			return (zfs_standard_error(hdl, errno, errbuf));
2570 		}
2571 	}
2572 	return (err != 0);
2573 }
2574 
2575 /*
2576  * Routines specific to "zfs recv"
2577  */
2578 
2579 static int
2580 recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
2581     boolean_t byteswap, zio_cksum_t *zc)
2582 {
2583 	char *cp = buf;
2584 	int rv;
2585 	int len = ilen;
2586 
2587 	do {
2588 		rv = read(fd, cp, len);
2589 		cp += rv;
2590 		len -= rv;
2591 	} while (rv > 0);
2592 
2593 	if (rv < 0 || len != 0) {
2594 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2595 		    "failed to read from stream"));
2596 		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
2597 		    "cannot receive")));
2598 	}
2599 
2600 	if (zc) {
2601 		if (byteswap)
2602 			fletcher_4_incremental_byteswap(buf, ilen, zc);
2603 		else
2604 			fletcher_4_incremental_native(buf, ilen, zc);
2605 	}
2606 	return (0);
2607 }
2608 
2609 static int
2610 recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
2611     boolean_t byteswap, zio_cksum_t *zc)
2612 {
2613 	char *buf;
2614 	int err;
2615 
2616 	buf = zfs_alloc(hdl, len);
2617 	if (buf == NULL)
2618 		return (ENOMEM);
2619 
2620 	if (len > hdl->libzfs_max_nvlist) {
2621 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "nvlist too large"));
2622 		free(buf);
2623 		return (ENOMEM);
2624 	}
2625 
2626 	err = recv_read(hdl, fd, buf, len, byteswap, zc);
2627 	if (err != 0) {
2628 		free(buf);
2629 		return (err);
2630 	}
2631 
2632 	err = nvlist_unpack(buf, len, nvp, 0);
2633 	free(buf);
2634 	if (err != 0) {
2635 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2636 		    "stream (malformed nvlist)"));
2637 		return (EINVAL);
2638 	}
2639 	return (0);
2640 }
2641 
2642 /*
2643  * Returns the grand origin (origin of origin of origin...) of a given handle.
2644  * If this dataset is not a clone, it simply returns a copy of the original
2645  * handle.
2646  */
2647 static zfs_handle_t *
2648 recv_open_grand_origin(zfs_handle_t *zhp)
2649 {
2650 	char origin[ZFS_MAX_DATASET_NAME_LEN];
2651 	zprop_source_t src;
2652 	zfs_handle_t *ozhp = zfs_handle_dup(zhp);
2653 
2654 	while (ozhp != NULL) {
2655 		if (zfs_prop_get(ozhp, ZFS_PROP_ORIGIN, origin,
2656 		    sizeof (origin), &src, NULL, 0, B_FALSE) != 0)
2657 			break;
2658 
2659 		(void) zfs_close(ozhp);
2660 		ozhp = zfs_open(zhp->zfs_hdl, origin, ZFS_TYPE_FILESYSTEM);
2661 	}
2662 
2663 	return (ozhp);
2664 }
2665 
2666 static int
2667 recv_rename_impl(zfs_handle_t *zhp, const char *name, const char *newname)
2668 {
2669 	int err;
2670 	zfs_handle_t *ozhp = NULL;
2671 
2672 	/*
2673 	 * Attempt to rename the dataset. If it fails with EACCES we have
2674 	 * attempted to rename the dataset outside of its encryption root.
2675 	 * Force the dataset to become an encryption root and try again.
2676 	 */
2677 	err = lzc_rename(name, newname);
2678 	if (err == EACCES) {
2679 		ozhp = recv_open_grand_origin(zhp);
2680 		if (ozhp == NULL) {
2681 			err = ENOENT;
2682 			goto out;
2683 		}
2684 
2685 		err = lzc_change_key(ozhp->zfs_name, DCP_CMD_FORCE_NEW_KEY,
2686 		    NULL, NULL, 0);
2687 		if (err != 0)
2688 			goto out;
2689 
2690 		err = lzc_rename(name, newname);
2691 	}
2692 
2693 out:
2694 	if (ozhp != NULL)
2695 		zfs_close(ozhp);
2696 	return (err);
2697 }
2698 
2699 static int
2700 recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
2701     int baselen, char *newname, recvflags_t *flags)
2702 {
2703 	static int seq;
2704 	int err;
2705 	prop_changelist_t *clp = NULL;
2706 	zfs_handle_t *zhp = NULL;
2707 
2708 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2709 	if (zhp == NULL) {
2710 		err = -1;
2711 		goto out;
2712 	}
2713 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2714 	    flags->force ? MS_FORCE : 0);
2715 	if (clp == NULL) {
2716 		err = -1;
2717 		goto out;
2718 	}
2719 	err = changelist_prefix(clp);
2720 	if (err)
2721 		goto out;
2722 
2723 	if (tryname) {
2724 		(void) strcpy(newname, tryname);
2725 		if (flags->verbose) {
2726 			(void) printf("attempting rename %s to %s\n",
2727 			    name, newname);
2728 		}
2729 		err = recv_rename_impl(zhp, name, newname);
2730 		if (err == 0)
2731 			changelist_rename(clp, name, tryname);
2732 	} else {
2733 		err = ENOENT;
2734 	}
2735 
2736 	if (err != 0 && strncmp(name + baselen, "recv-", 5) != 0) {
2737 		seq++;
2738 
2739 		(void) snprintf(newname, ZFS_MAX_DATASET_NAME_LEN,
2740 		    "%.*srecv-%u-%u", baselen, name, getpid(), seq);
2741 
2742 		if (flags->verbose) {
2743 			(void) printf("failed - trying rename %s to %s\n",
2744 			    name, newname);
2745 		}
2746 		err = recv_rename_impl(zhp, name, newname);
2747 		if (err == 0)
2748 			changelist_rename(clp, name, newname);
2749 		if (err && flags->verbose) {
2750 			(void) printf("failed (%u) - "
2751 			    "will try again on next pass\n", errno);
2752 		}
2753 		err = EAGAIN;
2754 	} else if (flags->verbose) {
2755 		if (err == 0)
2756 			(void) printf("success\n");
2757 		else
2758 			(void) printf("failed (%u)\n", errno);
2759 	}
2760 
2761 	(void) changelist_postfix(clp);
2762 
2763 out:
2764 	if (clp != NULL)
2765 		changelist_free(clp);
2766 	if (zhp != NULL)
2767 		zfs_close(zhp);
2768 
2769 	return (err);
2770 }
2771 
2772 static int
2773 recv_promote(libzfs_handle_t *hdl, const char *fsname,
2774     const char *origin_fsname, recvflags_t *flags)
2775 {
2776 	int err;
2777 	zfs_cmd_t zc = {"\0"};
2778 	zfs_handle_t *zhp = NULL, *ozhp = NULL;
2779 
2780 	if (flags->verbose)
2781 		(void) printf("promoting %s\n", fsname);
2782 
2783 	(void) strlcpy(zc.zc_value, origin_fsname, sizeof (zc.zc_value));
2784 	(void) strlcpy(zc.zc_name, fsname, sizeof (zc.zc_name));
2785 
2786 	/*
2787 	 * Attempt to promote the dataset. If it fails with EACCES the
2788 	 * promotion would cause this dataset to leave its encryption root.
2789 	 * Force the origin to become an encryption root and try again.
2790 	 */
2791 	err = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2792 	if (err == EACCES) {
2793 		zhp = zfs_open(hdl, fsname, ZFS_TYPE_DATASET);
2794 		if (zhp == NULL) {
2795 			err = -1;
2796 			goto out;
2797 		}
2798 
2799 		ozhp = recv_open_grand_origin(zhp);
2800 		if (ozhp == NULL) {
2801 			err = -1;
2802 			goto out;
2803 		}
2804 
2805 		err = lzc_change_key(ozhp->zfs_name, DCP_CMD_FORCE_NEW_KEY,
2806 		    NULL, NULL, 0);
2807 		if (err != 0)
2808 			goto out;
2809 
2810 		err = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
2811 	}
2812 
2813 out:
2814 	if (zhp != NULL)
2815 		zfs_close(zhp);
2816 	if (ozhp != NULL)
2817 		zfs_close(ozhp);
2818 
2819 	return (err);
2820 }
2821 
2822 static int
2823 recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
2824     char *newname, recvflags_t *flags)
2825 {
2826 	int err = 0;
2827 	prop_changelist_t *clp;
2828 	zfs_handle_t *zhp;
2829 	boolean_t defer = B_FALSE;
2830 	int spa_version;
2831 
2832 	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
2833 	if (zhp == NULL)
2834 		return (-1);
2835 	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
2836 	    flags->force ? MS_FORCE : 0);
2837 	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
2838 	    zfs_spa_version(zhp, &spa_version) == 0 &&
2839 	    spa_version >= SPA_VERSION_USERREFS)
2840 		defer = B_TRUE;
2841 	zfs_close(zhp);
2842 	if (clp == NULL)
2843 		return (-1);
2844 	err = changelist_prefix(clp);
2845 	if (err)
2846 		return (err);
2847 
2848 	if (flags->verbose)
2849 		(void) printf("attempting destroy %s\n", name);
2850 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
2851 		nvlist_t *nv = fnvlist_alloc();
2852 		fnvlist_add_boolean(nv, name);
2853 		err = lzc_destroy_snaps(nv, defer, NULL);
2854 		fnvlist_free(nv);
2855 	} else {
2856 		err = lzc_destroy(name);
2857 	}
2858 	if (err == 0) {
2859 		if (flags->verbose)
2860 			(void) printf("success\n");
2861 		changelist_remove(clp, name);
2862 	}
2863 
2864 	(void) changelist_postfix(clp);
2865 	changelist_free(clp);
2866 
2867 	/*
2868 	 * Deferred destroy might destroy the snapshot or only mark it to be
2869 	 * destroyed later, and it returns success in either case.
2870 	 */
2871 	if (err != 0 || (defer && zfs_dataset_exists(hdl, name,
2872 	    ZFS_TYPE_SNAPSHOT))) {
2873 		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
2874 	}
2875 
2876 	return (err);
2877 }
2878 
2879 typedef struct guid_to_name_data {
2880 	uint64_t guid;
2881 	boolean_t bookmark_ok;
2882 	char *name;
2883 	char *skip;
2884 	uint64_t *redact_snap_guids;
2885 	uint64_t num_redact_snaps;
2886 } guid_to_name_data_t;
2887 
2888 static boolean_t
2889 redact_snaps_match(zfs_handle_t *zhp, guid_to_name_data_t *gtnd)
2890 {
2891 	uint64_t *bmark_snaps;
2892 	uint_t bmark_num_snaps;
2893 	nvlist_t *nvl;
2894 	if (zhp->zfs_type != ZFS_TYPE_BOOKMARK)
2895 		return (B_FALSE);
2896 
2897 	nvl = fnvlist_lookup_nvlist(zhp->zfs_props,
2898 	    zfs_prop_to_name(ZFS_PROP_REDACT_SNAPS));
2899 	bmark_snaps = fnvlist_lookup_uint64_array(nvl, ZPROP_VALUE,
2900 	    &bmark_num_snaps);
2901 	if (bmark_num_snaps != gtnd->num_redact_snaps)
2902 		return (B_FALSE);
2903 	int i = 0;
2904 	for (; i < bmark_num_snaps; i++) {
2905 		int j = 0;
2906 		for (; j < bmark_num_snaps; j++) {
2907 			if (bmark_snaps[i] == gtnd->redact_snap_guids[j])
2908 				break;
2909 		}
2910 		if (j == bmark_num_snaps)
2911 			break;
2912 	}
2913 	return (i == bmark_num_snaps);
2914 }
2915 
2916 static int
2917 guid_to_name_cb(zfs_handle_t *zhp, void *arg)
2918 {
2919 	guid_to_name_data_t *gtnd = arg;
2920 	const char *slash;
2921 	int err;
2922 
2923 	if (gtnd->skip != NULL &&
2924 	    (slash = strrchr(zhp->zfs_name, '/')) != NULL &&
2925 	    strcmp(slash + 1, gtnd->skip) == 0) {
2926 		zfs_close(zhp);
2927 		return (0);
2928 	}
2929 
2930 	if (zfs_prop_get_int(zhp, ZFS_PROP_GUID) == gtnd->guid &&
2931 	    (gtnd->num_redact_snaps == -1 || redact_snaps_match(zhp, gtnd))) {
2932 		(void) strcpy(gtnd->name, zhp->zfs_name);
2933 		zfs_close(zhp);
2934 		return (EEXIST);
2935 	}
2936 
2937 	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
2938 	if (err != EEXIST && gtnd->bookmark_ok)
2939 		err = zfs_iter_bookmarks(zhp, guid_to_name_cb, gtnd);
2940 	zfs_close(zhp);
2941 	return (err);
2942 }
2943 
2944 /*
2945  * Attempt to find the local dataset associated with this guid.  In the case of
2946  * multiple matches, we attempt to find the "best" match by searching
2947  * progressively larger portions of the hierarchy.  This allows one to send a
2948  * tree of datasets individually and guarantee that we will find the source
2949  * guid within that hierarchy, even if there are multiple matches elsewhere.
2950  *
2951  * If num_redact_snaps is not -1, we attempt to find a redaction bookmark with
2952  * the specified number of redaction snapshots.  If num_redact_snaps isn't 0 or
2953  * -1, then redact_snap_guids will be an array of the guids of the snapshots the
2954  * redaction bookmark was created with.  If num_redact_snaps is -1, then we will
2955  * attempt to find a snapshot or bookmark (if bookmark_ok is passed) with the
2956  * given guid.  Note that a redaction bookmark can be returned if
2957  * num_redact_snaps == -1.
2958  */
2959 static int
2960 guid_to_name_redact_snaps(libzfs_handle_t *hdl, const char *parent,
2961     uint64_t guid, boolean_t bookmark_ok, uint64_t *redact_snap_guids,
2962     uint64_t num_redact_snaps, char *name)
2963 {
2964 	char pname[ZFS_MAX_DATASET_NAME_LEN];
2965 	guid_to_name_data_t gtnd;
2966 
2967 	gtnd.guid = guid;
2968 	gtnd.bookmark_ok = bookmark_ok;
2969 	gtnd.name = name;
2970 	gtnd.skip = NULL;
2971 	gtnd.redact_snap_guids = redact_snap_guids;
2972 	gtnd.num_redact_snaps = num_redact_snaps;
2973 
2974 	/*
2975 	 * Search progressively larger portions of the hierarchy, starting
2976 	 * with the filesystem specified by 'parent'.  This will
2977 	 * select the "most local" version of the origin snapshot in the case
2978 	 * that there are multiple matching snapshots in the system.
2979 	 */
2980 	(void) strlcpy(pname, parent, sizeof (pname));
2981 	char *cp = strrchr(pname, '@');
2982 	if (cp == NULL)
2983 		cp = strchr(pname, '\0');
2984 	for (; cp != NULL; cp = strrchr(pname, '/')) {
2985 		/* Chop off the last component and open the parent */
2986 		*cp = '\0';
2987 		zfs_handle_t *zhp = make_dataset_handle(hdl, pname);
2988 
2989 		if (zhp == NULL)
2990 			continue;
2991 		int err = guid_to_name_cb(zfs_handle_dup(zhp), &gtnd);
2992 		if (err != EEXIST)
2993 			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
2994 		if (err != EEXIST && bookmark_ok)
2995 			err = zfs_iter_bookmarks(zhp, guid_to_name_cb, &gtnd);
2996 		zfs_close(zhp);
2997 		if (err == EEXIST)
2998 			return (0);
2999 
3000 		/*
3001 		 * Remember the last portion of the dataset so we skip it next
3002 		 * time through (as we've already searched that portion of the
3003 		 * hierarchy).
3004 		 */
3005 		gtnd.skip = strrchr(pname, '/') + 1;
3006 	}
3007 
3008 	return (ENOENT);
3009 }
3010 
3011 static int
3012 guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
3013     boolean_t bookmark_ok, char *name)
3014 {
3015 	return (guid_to_name_redact_snaps(hdl, parent, guid, bookmark_ok, NULL,
3016 	    -1, name));
3017 }
3018 
3019 /*
3020  * Return +1 if guid1 is before guid2, 0 if they are the same, and -1 if
3021  * guid1 is after guid2.
3022  */
3023 static int
3024 created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
3025     uint64_t guid1, uint64_t guid2)
3026 {
3027 	nvlist_t *nvfs;
3028 	char *fsname = NULL, *snapname = NULL;
3029 	char buf[ZFS_MAX_DATASET_NAME_LEN];
3030 	int rv;
3031 	zfs_handle_t *guid1hdl, *guid2hdl;
3032 	uint64_t create1, create2;
3033 
3034 	if (guid2 == 0)
3035 		return (0);
3036 	if (guid1 == 0)
3037 		return (1);
3038 
3039 	nvfs = fsavl_find(avl, guid1, &snapname);
3040 	fsname = fnvlist_lookup_string(nvfs, "name");
3041 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
3042 	guid1hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
3043 	if (guid1hdl == NULL)
3044 		return (-1);
3045 
3046 	nvfs = fsavl_find(avl, guid2, &snapname);
3047 	fsname = fnvlist_lookup_string(nvfs, "name");
3048 	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
3049 	guid2hdl = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
3050 	if (guid2hdl == NULL) {
3051 		zfs_close(guid1hdl);
3052 		return (-1);
3053 	}
3054 
3055 	create1 = zfs_prop_get_int(guid1hdl, ZFS_PROP_CREATETXG);
3056 	create2 = zfs_prop_get_int(guid2hdl, ZFS_PROP_CREATETXG);
3057 
3058 	if (create1 < create2)
3059 		rv = -1;
3060 	else if (create1 > create2)
3061 		rv = +1;
3062 	else
3063 		rv = 0;
3064 
3065 	zfs_close(guid1hdl);
3066 	zfs_close(guid2hdl);
3067 
3068 	return (rv);
3069 }
3070 
3071 /*
3072  * This function reestablishes the hierarchy of encryption roots after a
3073  * recursive incremental receive has completed. This must be done after the
3074  * second call to recv_incremental_replication() has renamed and promoted all
3075  * sent datasets to their final locations in the dataset hierarchy.
3076  */
3077 static int
3078 recv_fix_encryption_hierarchy(libzfs_handle_t *hdl, const char *top_zfs,
3079     nvlist_t *stream_nv, avl_tree_t *stream_avl)
3080 {
3081 	int err;
3082 	nvpair_t *fselem = NULL;
3083 	nvlist_t *stream_fss;
3084 
3085 	stream_fss = fnvlist_lookup_nvlist(stream_nv, "fss");
3086 
3087 	while ((fselem = nvlist_next_nvpair(stream_fss, fselem)) != NULL) {
3088 		zfs_handle_t *zhp = NULL;
3089 		uint64_t crypt;
3090 		nvlist_t *snaps, *props, *stream_nvfs = NULL;
3091 		nvpair_t *snapel = NULL;
3092 		boolean_t is_encroot, is_clone, stream_encroot;
3093 		char *cp;
3094 		char *stream_keylocation = NULL;
3095 		char keylocation[MAXNAMELEN];
3096 		char fsname[ZFS_MAX_DATASET_NAME_LEN];
3097 
3098 		keylocation[0] = '\0';
3099 		stream_nvfs = fnvpair_value_nvlist(fselem);
3100 		snaps = fnvlist_lookup_nvlist(stream_nvfs, "snaps");
3101 		props = fnvlist_lookup_nvlist(stream_nvfs, "props");
3102 		stream_encroot = nvlist_exists(stream_nvfs, "is_encroot");
3103 
3104 		/* find a snapshot from the stream that exists locally */
3105 		err = ENOENT;
3106 		while ((snapel = nvlist_next_nvpair(snaps, snapel)) != NULL) {
3107 			uint64_t guid;
3108 
3109 			guid = fnvpair_value_uint64(snapel);
3110 			err = guid_to_name(hdl, top_zfs, guid, B_FALSE,
3111 			    fsname);
3112 			if (err == 0)
3113 				break;
3114 		}
3115 
3116 		if (err != 0)
3117 			continue;
3118 
3119 		cp = strchr(fsname, '@');
3120 		if (cp != NULL)
3121 			*cp = '\0';
3122 
3123 		zhp = zfs_open(hdl, fsname, ZFS_TYPE_DATASET);
3124 		if (zhp == NULL) {
3125 			err = ENOENT;
3126 			goto error;
3127 		}
3128 
3129 		crypt = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
3130 		is_clone = zhp->zfs_dmustats.dds_origin[0] != '\0';
3131 		(void) zfs_crypto_get_encryption_root(zhp, &is_encroot, NULL);
3132 
3133 		/* we don't need to do anything for unencrypted datasets */
3134 		if (crypt == ZIO_CRYPT_OFF) {
3135 			zfs_close(zhp);
3136 			continue;
3137 		}
3138 
3139 		/*
3140 		 * If the dataset is flagged as an encryption root, was not
3141 		 * received as a clone and is not currently an encryption root,
3142 		 * force it to become one. Fixup the keylocation if necessary.
3143 		 */
3144 		if (stream_encroot) {
3145 			if (!is_clone && !is_encroot) {
3146 				err = lzc_change_key(fsname,
3147 				    DCP_CMD_FORCE_NEW_KEY, NULL, NULL, 0);
3148 				if (err != 0) {
3149 					zfs_close(zhp);
3150 					goto error;
3151 				}
3152 			}
3153 
3154 			stream_keylocation = fnvlist_lookup_string(props,
3155 			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION));
3156 
3157 			/*
3158 			 * Refresh the properties in case the call to
3159 			 * lzc_change_key() changed the value.
3160 			 */
3161 			zfs_refresh_properties(zhp);
3162 			err = zfs_prop_get(zhp, ZFS_PROP_KEYLOCATION,
3163 			    keylocation, sizeof (keylocation), NULL, NULL,
3164 			    0, B_TRUE);
3165 			if (err != 0) {
3166 				zfs_close(zhp);
3167 				goto error;
3168 			}
3169 
3170 			if (strcmp(keylocation, stream_keylocation) != 0) {
3171 				err = zfs_prop_set(zhp,
3172 				    zfs_prop_to_name(ZFS_PROP_KEYLOCATION),
3173 				    stream_keylocation);
3174 				if (err != 0) {
3175 					zfs_close(zhp);
3176 					goto error;
3177 				}
3178 			}
3179 		}
3180 
3181 		/*
3182 		 * If the dataset is not flagged as an encryption root and is
3183 		 * currently an encryption root, force it to inherit from its
3184 		 * parent. The root of a raw send should never be
3185 		 * force-inherited.
3186 		 */
3187 		if (!stream_encroot && is_encroot &&
3188 		    strcmp(top_zfs, fsname) != 0) {
3189 			err = lzc_change_key(fsname, DCP_CMD_FORCE_INHERIT,
3190 			    NULL, NULL, 0);
3191 			if (err != 0) {
3192 				zfs_close(zhp);
3193 				goto error;
3194 			}
3195 		}
3196 
3197 		zfs_close(zhp);
3198 	}
3199 
3200 	return (0);
3201 
3202 error:
3203 	return (err);
3204 }
3205 
3206 static int
3207 recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
3208     recvflags_t *flags, nvlist_t *stream_nv, avl_tree_t *stream_avl,
3209     nvlist_t *renamed)
3210 {
3211 	nvlist_t *local_nv, *deleted = NULL;
3212 	avl_tree_t *local_avl;
3213 	nvpair_t *fselem, *nextfselem;
3214 	char *fromsnap;
3215 	char newname[ZFS_MAX_DATASET_NAME_LEN];
3216 	char guidname[32];
3217 	int error;
3218 	boolean_t needagain, progress, recursive;
3219 	char *s1, *s2;
3220 
3221 	fromsnap = fnvlist_lookup_string(stream_nv, "fromsnap");
3222 
3223 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
3224 	    ENOENT);
3225 
3226 	if (flags->dryrun)
3227 		return (0);
3228 
3229 again:
3230 	needagain = progress = B_FALSE;
3231 
3232 	deleted = fnvlist_alloc();
3233 
3234 	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
3235 	    recursive, B_TRUE, B_FALSE, recursive, B_FALSE, B_FALSE, B_FALSE,
3236 	    B_FALSE, B_TRUE, &local_nv, &local_avl)) != 0)
3237 		return (error);
3238 
3239 	/*
3240 	 * Process deletes and renames
3241 	 */
3242 	for (fselem = nvlist_next_nvpair(local_nv, NULL);
3243 	    fselem; fselem = nextfselem) {
3244 		nvlist_t *nvfs, *snaps;
3245 		nvlist_t *stream_nvfs = NULL;
3246 		nvpair_t *snapelem, *nextsnapelem;
3247 		uint64_t fromguid = 0;
3248 		uint64_t originguid = 0;
3249 		uint64_t stream_originguid = 0;
3250 		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
3251 		char *fsname, *stream_fsname;
3252 
3253 		nextfselem = nvlist_next_nvpair(local_nv, fselem);
3254 
3255 		nvfs = fnvpair_value_nvlist(fselem);
3256 		snaps = fnvlist_lookup_nvlist(nvfs, "snaps");
3257 		fsname = fnvlist_lookup_string(nvfs, "name");
3258 		parent_fromsnap_guid = fnvlist_lookup_uint64(nvfs,
3259 		    "parentfromsnap");
3260 		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
3261 
3262 		/*
3263 		 * First find the stream's fs, so we can check for
3264 		 * a different origin (due to "zfs promote")
3265 		 */
3266 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
3267 		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
3268 			uint64_t thisguid;
3269 
3270 			thisguid = fnvpair_value_uint64(snapelem);
3271 			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
3272 
3273 			if (stream_nvfs != NULL)
3274 				break;
3275 		}
3276 
3277 		/* check for promote */
3278 		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
3279 		    &stream_originguid);
3280 		if (stream_nvfs && originguid != stream_originguid) {
3281 			switch (created_before(hdl, local_avl,
3282 			    stream_originguid, originguid)) {
3283 			case 1: {
3284 				/* promote it! */
3285 				nvlist_t *origin_nvfs;
3286 				char *origin_fsname;
3287 
3288 				origin_nvfs = fsavl_find(local_avl, originguid,
3289 				    NULL);
3290 				origin_fsname = fnvlist_lookup_string(
3291 				    origin_nvfs, "name");
3292 				error = recv_promote(hdl, fsname, origin_fsname,
3293 				    flags);
3294 				if (error == 0)
3295 					progress = B_TRUE;
3296 				break;
3297 			}
3298 			default:
3299 				break;
3300 			case -1:
3301 				fsavl_destroy(local_avl);
3302 				fnvlist_free(local_nv);
3303 				return (-1);
3304 			}
3305 			/*
3306 			 * We had/have the wrong origin, therefore our
3307 			 * list of snapshots is wrong.  Need to handle
3308 			 * them on the next pass.
3309 			 */
3310 			needagain = B_TRUE;
3311 			continue;
3312 		}
3313 
3314 		for (snapelem = nvlist_next_nvpair(snaps, NULL);
3315 		    snapelem; snapelem = nextsnapelem) {
3316 			uint64_t thisguid;
3317 			char *stream_snapname;
3318 			nvlist_t *found, *props;
3319 
3320 			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
3321 
3322 			thisguid = fnvpair_value_uint64(snapelem);
3323 			found = fsavl_find(stream_avl, thisguid,
3324 			    &stream_snapname);
3325 
3326 			/* check for delete */
3327 			if (found == NULL) {
3328 				char name[ZFS_MAX_DATASET_NAME_LEN];
3329 
3330 				if (!flags->force)
3331 					continue;
3332 
3333 				(void) snprintf(name, sizeof (name), "%s@%s",
3334 				    fsname, nvpair_name(snapelem));
3335 
3336 				error = recv_destroy(hdl, name,
3337 				    strlen(fsname)+1, newname, flags);
3338 				if (error)
3339 					needagain = B_TRUE;
3340 				else
3341 					progress = B_TRUE;
3342 				sprintf(guidname, "%llu",
3343 				    (u_longlong_t)thisguid);
3344 				nvlist_add_boolean(deleted, guidname);
3345 				continue;
3346 			}
3347 
3348 			stream_nvfs = found;
3349 
3350 			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
3351 			    &props) && 0 == nvlist_lookup_nvlist(props,
3352 			    stream_snapname, &props)) {
3353 				zfs_cmd_t zc = {"\0"};
3354 
3355 				zc.zc_cookie = B_TRUE; /* received */
3356 				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
3357 				    "%s@%s", fsname, nvpair_name(snapelem));
3358 				if (zcmd_write_src_nvlist(hdl, &zc,
3359 				    props) == 0) {
3360 					(void) zfs_ioctl(hdl,
3361 					    ZFS_IOC_SET_PROP, &zc);
3362 					zcmd_free_nvlists(&zc);
3363 				}
3364 			}
3365 
3366 			/* check for different snapname */
3367 			if (strcmp(nvpair_name(snapelem),
3368 			    stream_snapname) != 0) {
3369 				char name[ZFS_MAX_DATASET_NAME_LEN];
3370 				char tryname[ZFS_MAX_DATASET_NAME_LEN];
3371 
3372 				(void) snprintf(name, sizeof (name), "%s@%s",
3373 				    fsname, nvpair_name(snapelem));
3374 				(void) snprintf(tryname, sizeof (name), "%s@%s",
3375 				    fsname, stream_snapname);
3376 
3377 				error = recv_rename(hdl, name, tryname,
3378 				    strlen(fsname)+1, newname, flags);
3379 				if (error)
3380 					needagain = B_TRUE;
3381 				else
3382 					progress = B_TRUE;
3383 			}
3384 
3385 			if (strcmp(stream_snapname, fromsnap) == 0)
3386 				fromguid = thisguid;
3387 		}
3388 
3389 		/* check for delete */
3390 		if (stream_nvfs == NULL) {
3391 			if (!flags->force)
3392 				continue;
3393 
3394 			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
3395 			    newname, flags);
3396 			if (error)
3397 				needagain = B_TRUE;
3398 			else
3399 				progress = B_TRUE;
3400 			sprintf(guidname, "%llu",
3401 			    (u_longlong_t)parent_fromsnap_guid);
3402 			nvlist_add_boolean(deleted, guidname);
3403 			continue;
3404 		}
3405 
3406 		if (fromguid == 0) {
3407 			if (flags->verbose) {
3408 				(void) printf("local fs %s does not have "
3409 				    "fromsnap (%s in stream); must have "
3410 				    "been deleted locally; ignoring\n",
3411 				    fsname, fromsnap);
3412 			}
3413 			continue;
3414 		}
3415 
3416 		stream_fsname = fnvlist_lookup_string(stream_nvfs, "name");
3417 		stream_parent_fromsnap_guid = fnvlist_lookup_uint64(
3418 		    stream_nvfs, "parentfromsnap");
3419 
3420 		s1 = strrchr(fsname, '/');
3421 		s2 = strrchr(stream_fsname, '/');
3422 
3423 		/*
3424 		 * Check if we're going to rename based on parent guid change
3425 		 * and the current parent guid was also deleted. If it was then
3426 		 * rename will fail and is likely unneeded, so avoid this and
3427 		 * force an early retry to determine the new
3428 		 * parent_fromsnap_guid.
3429 		 */
3430 		if (stream_parent_fromsnap_guid != 0 &&
3431 		    parent_fromsnap_guid != 0 &&
3432 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) {
3433 			sprintf(guidname, "%llu",
3434 			    (u_longlong_t)parent_fromsnap_guid);
3435 			if (nvlist_exists(deleted, guidname)) {
3436 				progress = B_TRUE;
3437 				needagain = B_TRUE;
3438 				goto doagain;
3439 			}
3440 		}
3441 
3442 		/*
3443 		 * Check for rename. If the exact receive path is specified, it
3444 		 * does not count as a rename, but we still need to check the
3445 		 * datasets beneath it.
3446 		 */
3447 		if ((stream_parent_fromsnap_guid != 0 &&
3448 		    parent_fromsnap_guid != 0 &&
3449 		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
3450 		    ((flags->isprefix || strcmp(tofs, fsname) != 0) &&
3451 		    (s1 != NULL) && (s2 != NULL) && strcmp(s1, s2) != 0)) {
3452 			nvlist_t *parent;
3453 			char tryname[ZFS_MAX_DATASET_NAME_LEN];
3454 
3455 			parent = fsavl_find(local_avl,
3456 			    stream_parent_fromsnap_guid, NULL);
3457 			/*
3458 			 * NB: parent might not be found if we used the
3459 			 * tosnap for stream_parent_fromsnap_guid,
3460 			 * because the parent is a newly-created fs;
3461 			 * we'll be able to rename it after we recv the
3462 			 * new fs.
3463 			 */
3464 			if (parent != NULL) {
3465 				char *pname;
3466 
3467 				pname = fnvlist_lookup_string(parent, "name");
3468 				(void) snprintf(tryname, sizeof (tryname),
3469 				    "%s%s", pname, strrchr(stream_fsname, '/'));
3470 			} else {
3471 				tryname[0] = '\0';
3472 				if (flags->verbose) {
3473 					(void) printf("local fs %s new parent "
3474 					    "not found\n", fsname);
3475 				}
3476 			}
3477 
3478 			newname[0] = '\0';
3479 
3480 			error = recv_rename(hdl, fsname, tryname,
3481 			    strlen(tofs)+1, newname, flags);
3482 
3483 			if (renamed != NULL && newname[0] != '\0') {
3484 				fnvlist_add_boolean(renamed, newname);
3485 			}
3486 
3487 			if (error)
3488 				needagain = B_TRUE;
3489 			else
3490 				progress = B_TRUE;
3491 		}
3492 	}
3493 
3494 doagain:
3495 	fsavl_destroy(local_avl);
3496 	fnvlist_free(local_nv);
3497 	fnvlist_free(deleted);
3498 
3499 	if (needagain && progress) {
3500 		/* do another pass to fix up temporary names */
3501 		if (flags->verbose)
3502 			(void) printf("another pass:\n");
3503 		goto again;
3504 	}
3505 
3506 	return (needagain || error != 0);
3507 }
3508 
3509 static int
3510 zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
3511     recvflags_t *flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
3512     char **top_zfs, nvlist_t *cmdprops)
3513 {
3514 	nvlist_t *stream_nv = NULL;
3515 	avl_tree_t *stream_avl = NULL;
3516 	char *fromsnap = NULL;
3517 	char *sendsnap = NULL;
3518 	char *cp;
3519 	char tofs[ZFS_MAX_DATASET_NAME_LEN];
3520 	char sendfs[ZFS_MAX_DATASET_NAME_LEN];
3521 	char errbuf[1024];
3522 	dmu_replay_record_t drre;
3523 	int error;
3524 	boolean_t anyerr = B_FALSE;
3525 	boolean_t softerr = B_FALSE;
3526 	boolean_t recursive, raw;
3527 
3528 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3529 	    "cannot receive"));
3530 
3531 	assert(drr->drr_type == DRR_BEGIN);
3532 	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
3533 	assert(DMU_GET_STREAM_HDRTYPE(drr->drr_u.drr_begin.drr_versioninfo) ==
3534 	    DMU_COMPOUNDSTREAM);
3535 
3536 	/*
3537 	 * Read in the nvlist from the stream.
3538 	 */
3539 	if (drr->drr_payloadlen != 0) {
3540 		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
3541 		    &stream_nv, flags->byteswap, zc);
3542 		if (error) {
3543 			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3544 			goto out;
3545 		}
3546 	}
3547 
3548 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
3549 	    ENOENT);
3550 	raw = (nvlist_lookup_boolean(stream_nv, "raw") == 0);
3551 
3552 	if (recursive && strchr(destname, '@')) {
3553 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3554 		    "cannot specify snapshot name for multi-snapshot stream"));
3555 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3556 		goto out;
3557 	}
3558 
3559 	/*
3560 	 * Read in the end record and verify checksum.
3561 	 */
3562 	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
3563 	    flags->byteswap, NULL)))
3564 		goto out;
3565 	if (flags->byteswap) {
3566 		drre.drr_type = BSWAP_32(drre.drr_type);
3567 		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
3568 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
3569 		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
3570 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
3571 		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
3572 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
3573 		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
3574 		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
3575 	}
3576 	if (drre.drr_type != DRR_END) {
3577 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3578 		goto out;
3579 	}
3580 	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
3581 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3582 		    "incorrect header checksum"));
3583 		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
3584 		goto out;
3585 	}
3586 
3587 	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
3588 
3589 	if (drr->drr_payloadlen != 0) {
3590 		nvlist_t *stream_fss;
3591 
3592 		stream_fss = fnvlist_lookup_nvlist(stream_nv, "fss");
3593 		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
3594 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3595 			    "couldn't allocate avl tree"));
3596 			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
3597 			goto out;
3598 		}
3599 
3600 		if (fromsnap != NULL && recursive) {
3601 			nvlist_t *renamed = NULL;
3602 			nvpair_t *pair = NULL;
3603 
3604 			(void) strlcpy(tofs, destname, sizeof (tofs));
3605 			if (flags->isprefix) {
3606 				struct drr_begin *drrb = &drr->drr_u.drr_begin;
3607 				int i;
3608 
3609 				if (flags->istail) {
3610 					cp = strrchr(drrb->drr_toname, '/');
3611 					if (cp == NULL) {
3612 						(void) strlcat(tofs, "/",
3613 						    sizeof (tofs));
3614 						i = 0;
3615 					} else {
3616 						i = (cp - drrb->drr_toname);
3617 					}
3618 				} else {
3619 					i = strcspn(drrb->drr_toname, "/@");
3620 				}
3621 				/* zfs_receive_one() will create_parents() */
3622 				(void) strlcat(tofs, &drrb->drr_toname[i],
3623 				    sizeof (tofs));
3624 				*strchr(tofs, '@') = '\0';
3625 			}
3626 
3627 			if (!flags->dryrun && !flags->nomount) {
3628 				renamed = fnvlist_alloc();
3629 			}
3630 
3631 			softerr = recv_incremental_replication(hdl, tofs, flags,
3632 			    stream_nv, stream_avl, renamed);
3633 
3634 			/* Unmount renamed filesystems before receiving. */
3635 			while ((pair = nvlist_next_nvpair(renamed,
3636 			    pair)) != NULL) {
3637 				zfs_handle_t *zhp;
3638 				prop_changelist_t *clp = NULL;
3639 
3640 				zhp = zfs_open(hdl, nvpair_name(pair),
3641 				    ZFS_TYPE_FILESYSTEM);
3642 				if (zhp != NULL) {
3643 					clp = changelist_gather(zhp,
3644 					    ZFS_PROP_MOUNTPOINT, 0,
3645 					    flags->forceunmount ? MS_FORCE : 0);
3646 					zfs_close(zhp);
3647 					if (clp != NULL) {
3648 						softerr |=
3649 						    changelist_prefix(clp);
3650 						changelist_free(clp);
3651 					}
3652 				}
3653 			}
3654 
3655 			fnvlist_free(renamed);
3656 		}
3657 	}
3658 
3659 	/*
3660 	 * Get the fs specified by the first path in the stream (the top level
3661 	 * specified by 'zfs send') and pass it to each invocation of
3662 	 * zfs_receive_one().
3663 	 */
3664 	(void) strlcpy(sendfs, drr->drr_u.drr_begin.drr_toname,
3665 	    sizeof (sendfs));
3666 	if ((cp = strchr(sendfs, '@')) != NULL) {
3667 		*cp = '\0';
3668 		/*
3669 		 * Find the "sendsnap", the final snapshot in a replication
3670 		 * stream.  zfs_receive_one() handles certain errors
3671 		 * differently, depending on if the contained stream is the
3672 		 * last one or not.
3673 		 */
3674 		sendsnap = (cp + 1);
3675 	}
3676 
3677 	/* Finally, receive each contained stream */
3678 	do {
3679 		/*
3680 		 * we should figure out if it has a recoverable
3681 		 * error, in which case do a recv_skip() and drive on.
3682 		 * Note, if we fail due to already having this guid,
3683 		 * zfs_receive_one() will take care of it (ie,
3684 		 * recv_skip() and return 0).
3685 		 */
3686 		error = zfs_receive_impl(hdl, destname, NULL, flags, fd,
3687 		    sendfs, stream_nv, stream_avl, top_zfs, sendsnap, cmdprops);
3688 		if (error == ENODATA) {
3689 			error = 0;
3690 			break;
3691 		}
3692 		anyerr |= error;
3693 	} while (error == 0);
3694 
3695 	if (drr->drr_payloadlen != 0 && recursive && fromsnap != NULL) {
3696 		/*
3697 		 * Now that we have the fs's they sent us, try the
3698 		 * renames again.
3699 		 */
3700 		softerr = recv_incremental_replication(hdl, tofs, flags,
3701 		    stream_nv, stream_avl, NULL);
3702 	}
3703 
3704 	if (raw && softerr == 0 && *top_zfs != NULL) {
3705 		softerr = recv_fix_encryption_hierarchy(hdl, *top_zfs,
3706 		    stream_nv, stream_avl);
3707 	}
3708 
3709 out:
3710 	fsavl_destroy(stream_avl);
3711 	fnvlist_free(stream_nv);
3712 	if (softerr)
3713 		error = -2;
3714 	if (anyerr)
3715 		error = -1;
3716 	return (error);
3717 }
3718 
3719 static void
3720 trunc_prop_errs(int truncated)
3721 {
3722 	ASSERT(truncated != 0);
3723 
3724 	if (truncated == 1)
3725 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
3726 		    "1 more property could not be set\n"));
3727 	else
3728 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
3729 		    "%d more properties could not be set\n"), truncated);
3730 }
3731 
3732 static int
3733 recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
3734 {
3735 	dmu_replay_record_t *drr;
3736 	void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
3737 	uint64_t payload_size;
3738 	char errbuf[1024];
3739 
3740 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
3741 	    "cannot receive"));
3742 
3743 	/* XXX would be great to use lseek if possible... */
3744 	drr = buf;
3745 
3746 	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
3747 	    byteswap, NULL) == 0) {
3748 		if (byteswap)
3749 			drr->drr_type = BSWAP_32(drr->drr_type);
3750 
3751 		switch (drr->drr_type) {
3752 		case DRR_BEGIN:
3753 			if (drr->drr_payloadlen != 0) {
3754 				(void) recv_read(hdl, fd, buf,
3755 				    drr->drr_payloadlen, B_FALSE, NULL);
3756 			}
3757 			break;
3758 
3759 		case DRR_END:
3760 			free(buf);
3761 			return (0);
3762 
3763 		case DRR_OBJECT:
3764 			if (byteswap) {
3765 				drr->drr_u.drr_object.drr_bonuslen =
3766 				    BSWAP_32(drr->drr_u.drr_object.
3767 				    drr_bonuslen);
3768 				drr->drr_u.drr_object.drr_raw_bonuslen =
3769 				    BSWAP_32(drr->drr_u.drr_object.
3770 				    drr_raw_bonuslen);
3771 			}
3772 
3773 			payload_size =
3774 			    DRR_OBJECT_PAYLOAD_SIZE(&drr->drr_u.drr_object);
3775 			(void) recv_read(hdl, fd, buf, payload_size,
3776 			    B_FALSE, NULL);
3777 			break;
3778 
3779 		case DRR_WRITE:
3780 			if (byteswap) {
3781 				drr->drr_u.drr_write.drr_logical_size =
3782 				    BSWAP_64(
3783 				    drr->drr_u.drr_write.drr_logical_size);
3784 				drr->drr_u.drr_write.drr_compressed_size =
3785 				    BSWAP_64(
3786 				    drr->drr_u.drr_write.drr_compressed_size);
3787 			}
3788 			payload_size =
3789 			    DRR_WRITE_PAYLOAD_SIZE(&drr->drr_u.drr_write);
3790 			assert(payload_size <= SPA_MAXBLOCKSIZE);
3791 			(void) recv_read(hdl, fd, buf,
3792 			    payload_size, B_FALSE, NULL);
3793 			break;
3794 		case DRR_SPILL:
3795 			if (byteswap) {
3796 				drr->drr_u.drr_spill.drr_length =
3797 				    BSWAP_64(drr->drr_u.drr_spill.drr_length);
3798 				drr->drr_u.drr_spill.drr_compressed_size =
3799 				    BSWAP_64(drr->drr_u.drr_spill.
3800 				    drr_compressed_size);
3801 			}
3802 
3803 			payload_size =
3804 			    DRR_SPILL_PAYLOAD_SIZE(&drr->drr_u.drr_spill);
3805 			(void) recv_read(hdl, fd, buf, payload_size,
3806 			    B_FALSE, NULL);
3807 			break;
3808 		case DRR_WRITE_EMBEDDED:
3809 			if (byteswap) {
3810 				drr->drr_u.drr_write_embedded.drr_psize =
3811 				    BSWAP_32(drr->drr_u.drr_write_embedded.
3812 				    drr_psize);
3813 			}
3814 			(void) recv_read(hdl, fd, buf,
3815 			    P2ROUNDUP(drr->drr_u.drr_write_embedded.drr_psize,
3816 			    8), B_FALSE, NULL);
3817 			break;
3818 		case DRR_OBJECT_RANGE:
3819 		case DRR_WRITE_BYREF:
3820 		case DRR_FREEOBJECTS:
3821 		case DRR_FREE:
3822 			break;
3823 
3824 		default:
3825 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3826 			    "invalid record type"));
3827 			free(buf);
3828 			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
3829 		}
3830 	}
3831 
3832 	free(buf);
3833 	return (-1);
3834 }
3835 
3836 static void
3837 recv_ecksum_set_aux(libzfs_handle_t *hdl, const char *target_snap,
3838     boolean_t resumable, boolean_t checksum)
3839 {
3840 	char target_fs[ZFS_MAX_DATASET_NAME_LEN];
3841 
3842 	zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, (checksum ?
3843 	    "checksum mismatch" : "incomplete stream")));
3844 
3845 	if (!resumable)
3846 		return;
3847 	(void) strlcpy(target_fs, target_snap, sizeof (target_fs));
3848 	*strchr(target_fs, '@') = '\0';
3849 	zfs_handle_t *zhp = zfs_open(hdl, target_fs,
3850 	    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
3851 	if (zhp == NULL)
3852 		return;
3853 
3854 	char token_buf[ZFS_MAXPROPLEN];
3855 	int error = zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN,
3856 	    token_buf, sizeof (token_buf),
3857 	    NULL, NULL, 0, B_TRUE);
3858 	if (error == 0) {
3859 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3860 		    "checksum mismatch or incomplete stream.\n"
3861 		    "Partially received snapshot is saved.\n"
3862 		    "A resuming stream can be generated on the sending "
3863 		    "system by running:\n"
3864 		    "    zfs send -t %s"),
3865 		    token_buf);
3866 	}
3867 	zfs_close(zhp);
3868 }
3869 
3870 /*
3871  * Prepare a new nvlist of properties that are to override (-o) or be excluded
3872  * (-x) from the received dataset
3873  * recvprops: received properties from the send stream
3874  * cmdprops: raw input properties from command line
3875  * origprops: properties, both locally-set and received, currently set on the
3876  *            target dataset if it exists, NULL otherwise.
3877  * oxprops: valid output override (-o) and excluded (-x) properties
3878  */
3879 static int
3880 zfs_setup_cmdline_props(libzfs_handle_t *hdl, zfs_type_t type,
3881     char *fsname, boolean_t zoned, boolean_t recursive, boolean_t newfs,
3882     boolean_t raw, boolean_t toplevel, nvlist_t *recvprops, nvlist_t *cmdprops,
3883     nvlist_t *origprops, nvlist_t **oxprops, uint8_t **wkeydata_out,
3884     uint_t *wkeylen_out, const char *errbuf)
3885 {
3886 	nvpair_t *nvp;
3887 	nvlist_t *oprops, *voprops;
3888 	zfs_handle_t *zhp = NULL;
3889 	zpool_handle_t *zpool_hdl = NULL;
3890 	char *cp;
3891 	int ret = 0;
3892 	char namebuf[ZFS_MAX_DATASET_NAME_LEN];
3893 
3894 	if (nvlist_empty(cmdprops))
3895 		return (0); /* No properties to override or exclude */
3896 
3897 	*oxprops = fnvlist_alloc();
3898 	oprops = fnvlist_alloc();
3899 
3900 	strlcpy(namebuf, fsname, ZFS_MAX_DATASET_NAME_LEN);
3901 
3902 	/*
3903 	 * Get our dataset handle. The target dataset may not exist yet.
3904 	 */
3905 	if (zfs_dataset_exists(hdl, namebuf, ZFS_TYPE_DATASET)) {
3906 		zhp = zfs_open(hdl, namebuf, ZFS_TYPE_DATASET);
3907 		if (zhp == NULL) {
3908 			ret = -1;
3909 			goto error;
3910 		}
3911 	}
3912 
3913 	/* open the zpool handle */
3914 	cp = strchr(namebuf, '/');
3915 	if (cp != NULL)
3916 		*cp = '\0';
3917 	zpool_hdl = zpool_open(hdl, namebuf);
3918 	if (zpool_hdl == NULL) {
3919 		ret = -1;
3920 		goto error;
3921 	}
3922 
3923 	/* restore namebuf to match fsname for later use */
3924 	if (cp != NULL)
3925 		*cp = '/';
3926 
3927 	/*
3928 	 * first iteration: process excluded (-x) properties now and gather
3929 	 * added (-o) properties to be later processed by zfs_valid_proplist()
3930 	 */
3931 	nvp = NULL;
3932 	while ((nvp = nvlist_next_nvpair(cmdprops, nvp)) != NULL) {
3933 		const char *name = nvpair_name(nvp);
3934 		zfs_prop_t prop = zfs_name_to_prop(name);
3935 
3936 		/* "origin" is processed separately, don't handle it here */
3937 		if (prop == ZFS_PROP_ORIGIN)
3938 			continue;
3939 
3940 		/* raw streams can't override encryption properties */
3941 		if ((zfs_prop_encryption_key_param(prop) ||
3942 		    prop == ZFS_PROP_ENCRYPTION) && raw) {
3943 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3944 			    "encryption property '%s' cannot "
3945 			    "be set or excluded for raw streams."), name);
3946 			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
3947 			goto error;
3948 		}
3949 
3950 		/* incremental streams can only exclude encryption properties */
3951 		if ((zfs_prop_encryption_key_param(prop) ||
3952 		    prop == ZFS_PROP_ENCRYPTION) && !newfs &&
3953 		    nvpair_type(nvp) != DATA_TYPE_BOOLEAN) {
3954 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
3955 			    "encryption property '%s' cannot "
3956 			    "be set for incremental streams."), name);
3957 			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
3958 			goto error;
3959 		}
3960 
3961 		switch (nvpair_type(nvp)) {
3962 		case DATA_TYPE_BOOLEAN: /* -x property */
3963 			/*
3964 			 * DATA_TYPE_BOOLEAN is the way we're asked to "exclude"
3965 			 * a property: this is done by forcing an explicit
3966 			 * inherit on the destination so the effective value is
3967 			 * not the one we received from the send stream.
3968 			 */
3969 			if (!zfs_prop_valid_for_type(prop, type, B_FALSE) &&
3970 			    !zfs_prop_user(name)) {
3971 				(void) fprintf(stderr, dgettext(TEXT_DOMAIN,
3972 				    "Warning: %s: property '%s' does not "
3973 				    "apply to datasets of this type\n"),
3974 				    fsname, name);
3975 				continue;
3976 			}
3977 			/*
3978 			 * We do this only if the property is not already
3979 			 * locally-set, in which case its value will take
3980 			 * priority over the received anyway.
3981 			 */
3982 			if (nvlist_exists(origprops, name)) {
3983 				nvlist_t *attrs;
3984 				char *source = NULL;
3985 
3986 				attrs = fnvlist_lookup_nvlist(origprops, name);
3987 				if (nvlist_lookup_string(attrs,
3988 				    ZPROP_SOURCE, &source) == 0 &&
3989 				    strcmp(source, ZPROP_SOURCE_VAL_RECVD) != 0)
3990 					continue;
3991 			}
3992 			/*
3993 			 * We can't force an explicit inherit on non-inheritable
3994 			 * properties: if we're asked to exclude this kind of
3995 			 * values we remove them from "recvprops" input nvlist.
3996 			 */
3997 			if (!zfs_prop_inheritable(prop) &&
3998 			    !zfs_prop_user(name) && /* can be inherited too */
3999 			    nvlist_exists(recvprops, name))
4000 				fnvlist_remove(recvprops, name);
4001 			else
4002 				fnvlist_add_nvpair(*oxprops, nvp);
4003 			break;
4004 		case DATA_TYPE_STRING: /* -o property=value */
4005 			/*
4006 			 * we're trying to override a property that does not
4007 			 * make sense for this type of dataset, but we don't
4008 			 * want to fail if the receive is recursive: this comes
4009 			 * in handy when the send stream contains, for
4010 			 * instance, a child ZVOL and we're trying to receive
4011 			 * it with "-o atime=on"
4012 			 */
4013 			if (!zfs_prop_valid_for_type(prop, type, B_FALSE) &&
4014 			    !zfs_prop_user(name)) {
4015 				if (recursive)
4016 					continue;
4017 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4018 				    "property '%s' does not apply to datasets "
4019 				    "of this type"), name);
4020 				ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
4021 				goto error;
4022 			}
4023 			fnvlist_add_nvpair(oprops, nvp);
4024 			break;
4025 		default:
4026 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4027 			    "property '%s' must be a string or boolean"), name);
4028 			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
4029 			goto error;
4030 		}
4031 	}
4032 
4033 	if (toplevel) {
4034 		/* convert override strings properties to native */
4035 		if ((voprops = zfs_valid_proplist(hdl, ZFS_TYPE_DATASET,
4036 		    oprops, zoned, zhp, zpool_hdl, B_FALSE, errbuf)) == NULL) {
4037 			ret = zfs_error(hdl, EZFS_BADPROP, errbuf);
4038 			goto error;
4039 		}
4040 
4041 		/*
4042 		 * zfs_crypto_create() requires the parent name. Get it
4043 		 * by truncating the fsname copy stored in namebuf.
4044 		 */
4045 		cp = strrchr(namebuf, '/');
4046 		if (cp != NULL)
4047 			*cp = '\0';
4048 
4049 		if (!raw && zfs_crypto_create(hdl, namebuf, voprops, NULL,
4050 		    B_FALSE, wkeydata_out, wkeylen_out) != 0) {
4051 			fnvlist_free(voprops);
4052 			ret = zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
4053 			goto error;
4054 		}
4055 
4056 		/* second pass: process "-o" properties */
4057 		fnvlist_merge(*oxprops, voprops);
4058 		fnvlist_free(voprops);
4059 	} else {
4060 		/* override props on child dataset are inherited */
4061 		nvp = NULL;
4062 		while ((nvp = nvlist_next_nvpair(oprops, nvp)) != NULL) {
4063 			const char *name = nvpair_name(nvp);
4064 			fnvlist_add_boolean(*oxprops, name);
4065 		}
4066 	}
4067 
4068 error:
4069 	if (zhp != NULL)
4070 		zfs_close(zhp);
4071 	if (zpool_hdl != NULL)
4072 		zpool_close(zpool_hdl);
4073 	fnvlist_free(oprops);
4074 	return (ret);
4075 }
4076 
4077 /*
4078  * Restores a backup of tosnap from the file descriptor specified by infd.
4079  */
4080 static int
4081 zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
4082     const char *originsnap, recvflags_t *flags, dmu_replay_record_t *drr,
4083     dmu_replay_record_t *drr_noswap, const char *sendfs, nvlist_t *stream_nv,
4084     avl_tree_t *stream_avl, char **top_zfs,
4085     const char *finalsnap, nvlist_t *cmdprops)
4086 {
4087 	time_t begin_time;
4088 	int ioctl_err, ioctl_errno, err;
4089 	char *cp;
4090 	struct drr_begin *drrb = &drr->drr_u.drr_begin;
4091 	char errbuf[1024];
4092 	const char *chopprefix;
4093 	boolean_t newfs = B_FALSE;
4094 	boolean_t stream_wantsnewfs, stream_resumingnewfs;
4095 	boolean_t newprops = B_FALSE;
4096 	uint64_t read_bytes = 0;
4097 	uint64_t errflags = 0;
4098 	uint64_t parent_snapguid = 0;
4099 	prop_changelist_t *clp = NULL;
4100 	nvlist_t *snapprops_nvlist = NULL;
4101 	nvlist_t *snapholds_nvlist = NULL;
4102 	zprop_errflags_t prop_errflags;
4103 	nvlist_t *prop_errors = NULL;
4104 	boolean_t recursive;
4105 	char *snapname = NULL;
4106 	char destsnap[MAXPATHLEN * 2];
4107 	char origin[MAXNAMELEN];
4108 	char name[MAXPATHLEN];
4109 	char tmp_keylocation[MAXNAMELEN];
4110 	nvlist_t *rcvprops = NULL; /* props received from the send stream */
4111 	nvlist_t *oxprops = NULL; /* override (-o) and exclude (-x) props */
4112 	nvlist_t *origprops = NULL; /* original props (if destination exists) */
4113 	zfs_type_t type;
4114 	boolean_t toplevel = B_FALSE;
4115 	boolean_t zoned = B_FALSE;
4116 	boolean_t hastoken = B_FALSE;
4117 	boolean_t redacted;
4118 	uint8_t *wkeydata = NULL;
4119 	uint_t wkeylen = 0;
4120 
4121 	begin_time = time(NULL);
4122 	bzero(origin, MAXNAMELEN);
4123 	bzero(tmp_keylocation, MAXNAMELEN);
4124 
4125 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4126 	    "cannot receive"));
4127 
4128 	recursive = (nvlist_lookup_boolean(stream_nv, "not_recursive") ==
4129 	    ENOENT);
4130 
4131 	/* Did the user request holds be skipped via zfs recv -k? */
4132 	boolean_t holds = flags->holds && !flags->skipholds;
4133 
4134 	if (stream_avl != NULL) {
4135 		char *keylocation = NULL;
4136 		nvlist_t *lookup = NULL;
4137 		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
4138 		    &snapname);
4139 
4140 		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
4141 		    &parent_snapguid);
4142 		err = nvlist_lookup_nvlist(fs, "props", &rcvprops);
4143 		if (err) {
4144 			rcvprops = fnvlist_alloc();
4145 			newprops = B_TRUE;
4146 		}
4147 
4148 		/*
4149 		 * The keylocation property may only be set on encryption roots,
4150 		 * but this dataset might not become an encryption root until
4151 		 * recv_fix_encryption_hierarchy() is called. That function
4152 		 * will fixup the keylocation anyway, so we temporarily unset
4153 		 * the keylocation for now to avoid any errors from the receive
4154 		 * ioctl.
4155 		 */
4156 		err = nvlist_lookup_string(rcvprops,
4157 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), &keylocation);
4158 		if (err == 0) {
4159 			strcpy(tmp_keylocation, keylocation);
4160 			(void) nvlist_remove_all(rcvprops,
4161 			    zfs_prop_to_name(ZFS_PROP_KEYLOCATION));
4162 		}
4163 
4164 		if (flags->canmountoff) {
4165 			fnvlist_add_uint64(rcvprops,
4166 			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0);
4167 		} else if (newprops) {	/* nothing in rcvprops, eliminate it */
4168 			fnvlist_free(rcvprops);
4169 			rcvprops = NULL;
4170 			newprops = B_FALSE;
4171 		}
4172 		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &lookup)) {
4173 			snapprops_nvlist = fnvlist_lookup_nvlist(lookup,
4174 			    snapname);
4175 		}
4176 		if (holds) {
4177 			if (0 == nvlist_lookup_nvlist(fs, "snapholds",
4178 			    &lookup)) {
4179 				snapholds_nvlist = fnvlist_lookup_nvlist(
4180 				    lookup, snapname);
4181 			}
4182 		}
4183 	}
4184 
4185 	cp = NULL;
4186 
4187 	/*
4188 	 * Determine how much of the snapshot name stored in the stream
4189 	 * we are going to tack on to the name they specified on the
4190 	 * command line, and how much we are going to chop off.
4191 	 *
4192 	 * If they specified a snapshot, chop the entire name stored in
4193 	 * the stream.
4194 	 */
4195 	if (flags->istail) {
4196 		/*
4197 		 * A filesystem was specified with -e. We want to tack on only
4198 		 * the tail of the sent snapshot path.
4199 		 */
4200 		if (strchr(tosnap, '@')) {
4201 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
4202 			    "argument - snapshot not allowed with -e"));
4203 			err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
4204 			goto out;
4205 		}
4206 
4207 		chopprefix = strrchr(sendfs, '/');
4208 
4209 		if (chopprefix == NULL) {
4210 			/*
4211 			 * The tail is the poolname, so we need to
4212 			 * prepend a path separator.
4213 			 */
4214 			int len = strlen(drrb->drr_toname);
4215 			cp = malloc(len + 2);
4216 			cp[0] = '/';
4217 			(void) strcpy(&cp[1], drrb->drr_toname);
4218 			chopprefix = cp;
4219 		} else {
4220 			chopprefix = drrb->drr_toname + (chopprefix - sendfs);
4221 		}
4222 	} else if (flags->isprefix) {
4223 		/*
4224 		 * A filesystem was specified with -d. We want to tack on
4225 		 * everything but the first element of the sent snapshot path
4226 		 * (all but the pool name).
4227 		 */
4228 		if (strchr(tosnap, '@')) {
4229 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
4230 			    "argument - snapshot not allowed with -d"));
4231 			err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
4232 			goto out;
4233 		}
4234 
4235 		chopprefix = strchr(drrb->drr_toname, '/');
4236 		if (chopprefix == NULL)
4237 			chopprefix = strchr(drrb->drr_toname, '@');
4238 	} else if (strchr(tosnap, '@') == NULL) {
4239 		/*
4240 		 * If a filesystem was specified without -d or -e, we want to
4241 		 * tack on everything after the fs specified by 'zfs send'.
4242 		 */
4243 		chopprefix = drrb->drr_toname + strlen(sendfs);
4244 	} else {
4245 		/* A snapshot was specified as an exact path (no -d or -e). */
4246 		if (recursive) {
4247 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4248 			    "cannot specify snapshot name for multi-snapshot "
4249 			    "stream"));
4250 			err = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4251 			goto out;
4252 		}
4253 		chopprefix = drrb->drr_toname + strlen(drrb->drr_toname);
4254 	}
4255 
4256 	ASSERT(strstr(drrb->drr_toname, sendfs) == drrb->drr_toname);
4257 	ASSERT(chopprefix > drrb->drr_toname || strchr(sendfs, '/') == NULL);
4258 	ASSERT(chopprefix <= drrb->drr_toname + strlen(drrb->drr_toname) ||
4259 	    strchr(sendfs, '/') == NULL);
4260 	ASSERT(chopprefix[0] == '/' || chopprefix[0] == '@' ||
4261 	    chopprefix[0] == '\0');
4262 
4263 	/*
4264 	 * Determine name of destination snapshot.
4265 	 */
4266 	(void) strlcpy(destsnap, tosnap, sizeof (destsnap));
4267 	(void) strlcat(destsnap, chopprefix, sizeof (destsnap));
4268 	free(cp);
4269 	if (!zfs_name_valid(destsnap, ZFS_TYPE_SNAPSHOT)) {
4270 		err = zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
4271 		goto out;
4272 	}
4273 
4274 	/*
4275 	 * Determine the name of the origin snapshot.
4276 	 */
4277 	if (originsnap) {
4278 		(void) strlcpy(origin, originsnap, sizeof (origin));
4279 		if (flags->verbose)
4280 			(void) printf("using provided clone origin %s\n",
4281 			    origin);
4282 	} else if (drrb->drr_flags & DRR_FLAG_CLONE) {
4283 		if (guid_to_name(hdl, destsnap,
4284 		    drrb->drr_fromguid, B_FALSE, origin) != 0) {
4285 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4286 			    "local origin for clone %s does not exist"),
4287 			    destsnap);
4288 			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4289 			goto out;
4290 		}
4291 		if (flags->verbose)
4292 			(void) printf("found clone origin %s\n", origin);
4293 	}
4294 
4295 	if ((DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
4296 	    DMU_BACKUP_FEATURE_DEDUP)) {
4297 		(void) fprintf(stderr,
4298 		    gettext("ERROR: \"zfs receive\" no longer supports "
4299 		    "deduplicated send streams.  Use\n"
4300 		    "the \"zstream redup\" command to convert this stream "
4301 		    "to a regular,\n"
4302 		    "non-deduplicated stream.\n"));
4303 		err = zfs_error(hdl, EZFS_NOTSUP, errbuf);
4304 		goto out;
4305 	}
4306 
4307 	boolean_t resuming = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
4308 	    DMU_BACKUP_FEATURE_RESUMING;
4309 	boolean_t raw = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
4310 	    DMU_BACKUP_FEATURE_RAW;
4311 	boolean_t embedded = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
4312 	    DMU_BACKUP_FEATURE_EMBED_DATA;
4313 	stream_wantsnewfs = (drrb->drr_fromguid == 0 ||
4314 	    (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && !resuming;
4315 	stream_resumingnewfs = (drrb->drr_fromguid == 0 ||
4316 	    (drrb->drr_flags & DRR_FLAG_CLONE) || originsnap) && resuming;
4317 
4318 	if (stream_wantsnewfs) {
4319 		/*
4320 		 * if the parent fs does not exist, look for it based on
4321 		 * the parent snap GUID
4322 		 */
4323 		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
4324 		    "cannot receive new filesystem stream"));
4325 
4326 		(void) strcpy(name, destsnap);
4327 		cp = strrchr(name, '/');
4328 		if (cp)
4329 			*cp = '\0';
4330 		if (cp &&
4331 		    !zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
4332 			char suffix[ZFS_MAX_DATASET_NAME_LEN];
4333 			(void) strcpy(suffix, strrchr(destsnap, '/'));
4334 			if (guid_to_name(hdl, name, parent_snapguid,
4335 			    B_FALSE, destsnap) == 0) {
4336 				*strchr(destsnap, '@') = '\0';
4337 				(void) strcat(destsnap, suffix);
4338 			}
4339 		}
4340 	} else {
4341 		/*
4342 		 * If the fs does not exist, look for it based on the
4343 		 * fromsnap GUID.
4344 		 */
4345 		if (resuming) {
4346 			(void) snprintf(errbuf, sizeof (errbuf),
4347 			    dgettext(TEXT_DOMAIN,
4348 			    "cannot receive resume stream"));
4349 		} else {
4350 			(void) snprintf(errbuf, sizeof (errbuf),
4351 			    dgettext(TEXT_DOMAIN,
4352 			    "cannot receive incremental stream"));
4353 		}
4354 
4355 		(void) strcpy(name, destsnap);
4356 		*strchr(name, '@') = '\0';
4357 
4358 		/*
4359 		 * If the exact receive path was specified and this is the
4360 		 * topmost path in the stream, then if the fs does not exist we
4361 		 * should look no further.
4362 		 */
4363 		if ((flags->isprefix || (*(chopprefix = drrb->drr_toname +
4364 		    strlen(sendfs)) != '\0' && *chopprefix != '@')) &&
4365 		    !zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
4366 			char snap[ZFS_MAX_DATASET_NAME_LEN];
4367 			(void) strcpy(snap, strchr(destsnap, '@'));
4368 			if (guid_to_name(hdl, name, drrb->drr_fromguid,
4369 			    B_FALSE, destsnap) == 0) {
4370 				*strchr(destsnap, '@') = '\0';
4371 				(void) strcat(destsnap, snap);
4372 			}
4373 		}
4374 	}
4375 
4376 	(void) strcpy(name, destsnap);
4377 	*strchr(name, '@') = '\0';
4378 
4379 	redacted = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo) &
4380 	    DMU_BACKUP_FEATURE_REDACTED;
4381 
4382 	if (zfs_dataset_exists(hdl, name, ZFS_TYPE_DATASET)) {
4383 		zfs_cmd_t zc = {"\0"};
4384 		zfs_handle_t *zhp;
4385 		boolean_t encrypted;
4386 
4387 		(void) strcpy(zc.zc_name, name);
4388 
4389 		/*
4390 		 * Destination fs exists.  It must be one of these cases:
4391 		 *  - an incremental send stream
4392 		 *  - the stream specifies a new fs (full stream or clone)
4393 		 *    and they want us to blow away the existing fs (and
4394 		 *    have therefore specified -F and removed any snapshots)
4395 		 *  - we are resuming a failed receive.
4396 		 */
4397 		if (stream_wantsnewfs) {
4398 			boolean_t is_volume = drrb->drr_type == DMU_OST_ZVOL;
4399 			if (!flags->force) {
4400 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4401 				    "destination '%s' exists\n"
4402 				    "must specify -F to overwrite it"), name);
4403 				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
4404 				goto out;
4405 			}
4406 			if (zfs_ioctl(hdl, ZFS_IOC_SNAPSHOT_LIST_NEXT,
4407 			    &zc) == 0) {
4408 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4409 				    "destination has snapshots (eg. %s)\n"
4410 				    "must destroy them to overwrite it"),
4411 				    zc.zc_name);
4412 				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
4413 				goto out;
4414 			}
4415 			if (is_volume && strrchr(name, '/') == NULL) {
4416 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4417 				    "destination %s is the root dataset\n"
4418 				    "cannot overwrite with a ZVOL"),
4419 				    name);
4420 				err = zfs_error(hdl, EZFS_EXISTS, errbuf);
4421 				goto out;
4422 			}
4423 			if (is_volume &&
4424 			    zfs_ioctl(hdl, ZFS_IOC_DATASET_LIST_NEXT,
4425 			    &zc) == 0) {
4426 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4427 				    "destination has children (eg. %s)\n"
4428 				    "cannot overwrite with a ZVOL"),
4429 				    zc.zc_name);
4430 				err = zfs_error(hdl, EZFS_WRONG_PARENT, errbuf);
4431 				goto out;
4432 			}
4433 		}
4434 
4435 		if ((zhp = zfs_open(hdl, name,
4436 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
4437 			err = -1;
4438 			goto out;
4439 		}
4440 
4441 		if (stream_wantsnewfs &&
4442 		    zhp->zfs_dmustats.dds_origin[0]) {
4443 			zfs_close(zhp);
4444 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4445 			    "destination '%s' is a clone\n"
4446 			    "must destroy it to overwrite it"), name);
4447 			err = zfs_error(hdl, EZFS_EXISTS, errbuf);
4448 			goto out;
4449 		}
4450 
4451 		/*
4452 		 * Raw sends can not be performed as an incremental on top
4453 		 * of existing unencrypted datasets. zfs recv -F can't be
4454 		 * used to blow away an existing encrypted filesystem. This
4455 		 * is because it would require the dsl dir to point to the
4456 		 * new key (or lack of a key) and the old key at the same
4457 		 * time. The -F flag may still be used for deleting
4458 		 * intermediate snapshots that would otherwise prevent the
4459 		 * receive from working.
4460 		 */
4461 		encrypted = zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION) !=
4462 		    ZIO_CRYPT_OFF;
4463 		if (!stream_wantsnewfs && !encrypted && raw) {
4464 			zfs_close(zhp);
4465 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4466 			    "cannot perform raw receive on top of "
4467 			    "existing unencrypted dataset"));
4468 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
4469 			goto out;
4470 		}
4471 
4472 		if (stream_wantsnewfs && flags->force &&
4473 		    ((raw && !encrypted) || encrypted)) {
4474 			zfs_close(zhp);
4475 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4476 			    "zfs receive -F cannot be used to destroy an "
4477 			    "encrypted filesystem or overwrite an "
4478 			    "unencrypted one with an encrypted one"));
4479 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
4480 			goto out;
4481 		}
4482 
4483 		if (!flags->dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
4484 		    (stream_wantsnewfs || stream_resumingnewfs)) {
4485 			/* We can't do online recv in this case */
4486 			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
4487 			    flags->forceunmount ? MS_FORCE : 0);
4488 			if (clp == NULL) {
4489 				zfs_close(zhp);
4490 				err = -1;
4491 				goto out;
4492 			}
4493 			if (changelist_prefix(clp) != 0) {
4494 				changelist_free(clp);
4495 				zfs_close(zhp);
4496 				err = -1;
4497 				goto out;
4498 			}
4499 		}
4500 
4501 		/*
4502 		 * If we are resuming a newfs, set newfs here so that we will
4503 		 * mount it if the recv succeeds this time.  We can tell
4504 		 * that it was a newfs on the first recv because the fs
4505 		 * itself will be inconsistent (if the fs existed when we
4506 		 * did the first recv, we would have received it into
4507 		 * .../%recv).
4508 		 */
4509 		if (resuming && zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT))
4510 			newfs = B_TRUE;
4511 
4512 		/* we want to know if we're zoned when validating -o|-x props */
4513 		zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
4514 
4515 		/* may need this info later, get it now we have zhp around */
4516 		if (zfs_prop_get(zhp, ZFS_PROP_RECEIVE_RESUME_TOKEN, NULL, 0,
4517 		    NULL, NULL, 0, B_TRUE) == 0)
4518 			hastoken = B_TRUE;
4519 
4520 		/* gather existing properties on destination */
4521 		origprops = fnvlist_alloc();
4522 		fnvlist_merge(origprops, zhp->zfs_props);
4523 		fnvlist_merge(origprops, zhp->zfs_user_props);
4524 
4525 		zfs_close(zhp);
4526 	} else {
4527 		zfs_handle_t *zhp;
4528 
4529 		/*
4530 		 * Destination filesystem does not exist.  Therefore we better
4531 		 * be creating a new filesystem (either from a full backup, or
4532 		 * a clone).  It would therefore be invalid if the user
4533 		 * specified only the pool name (i.e. if the destination name
4534 		 * contained no slash character).
4535 		 */
4536 		cp = strrchr(name, '/');
4537 
4538 		if (!stream_wantsnewfs || cp == NULL) {
4539 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4540 			    "destination '%s' does not exist"), name);
4541 			err = zfs_error(hdl, EZFS_NOENT, errbuf);
4542 			goto out;
4543 		}
4544 
4545 		/*
4546 		 * Trim off the final dataset component so we perform the
4547 		 * recvbackup ioctl to the filesystems's parent.
4548 		 */
4549 		*cp = '\0';
4550 
4551 		if (flags->isprefix && !flags->istail && !flags->dryrun &&
4552 		    create_parents(hdl, destsnap, strlen(tosnap)) != 0) {
4553 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
4554 			goto out;
4555 		}
4556 
4557 		/* validate parent */
4558 		zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
4559 		if (zhp == NULL) {
4560 			err = zfs_error(hdl, EZFS_BADRESTORE, errbuf);
4561 			goto out;
4562 		}
4563 		if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
4564 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4565 			    "parent '%s' is not a filesystem"), name);
4566 			err = zfs_error(hdl, EZFS_WRONG_PARENT, errbuf);
4567 			zfs_close(zhp);
4568 			goto out;
4569 		}
4570 
4571 		zfs_close(zhp);
4572 
4573 		newfs = B_TRUE;
4574 		*cp = '/';
4575 	}
4576 
4577 	if (flags->verbose) {
4578 		(void) printf("%s %s stream of %s into %s\n",
4579 		    flags->dryrun ? "would receive" : "receiving",
4580 		    drrb->drr_fromguid ? "incremental" : "full",
4581 		    drrb->drr_toname, destsnap);
4582 		(void) fflush(stdout);
4583 	}
4584 
4585 	/*
4586 	 * If this is the top-level dataset, record it so we can use it
4587 	 * for recursive operations later.
4588 	 */
4589 	if (top_zfs != NULL &&
4590 	    (*top_zfs == NULL || strcmp(*top_zfs, name) == 0)) {
4591 		toplevel = B_TRUE;
4592 		if (*top_zfs == NULL)
4593 			*top_zfs = zfs_strdup(hdl, name);
4594 	}
4595 
4596 	if (drrb->drr_type == DMU_OST_ZVOL) {
4597 		type = ZFS_TYPE_VOLUME;
4598 	} else if (drrb->drr_type == DMU_OST_ZFS) {
4599 		type = ZFS_TYPE_FILESYSTEM;
4600 	} else {
4601 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4602 		    "invalid record type: 0x%d"), drrb->drr_type);
4603 		err = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4604 		goto out;
4605 	}
4606 	if ((err = zfs_setup_cmdline_props(hdl, type, name, zoned, recursive,
4607 	    stream_wantsnewfs, raw, toplevel, rcvprops, cmdprops, origprops,
4608 	    &oxprops, &wkeydata, &wkeylen, errbuf)) != 0)
4609 		goto out;
4610 
4611 	/*
4612 	 * When sending with properties (zfs send -p), the encryption property
4613 	 * is not included because it is a SETONCE property and therefore
4614 	 * treated as read only. However, we are always able to determine its
4615 	 * value because raw sends will include it in the DRR_BDEGIN payload
4616 	 * and non-raw sends with properties are not allowed for encrypted
4617 	 * datasets. Therefore, if this is a non-raw properties stream, we can
4618 	 * infer that the value should be ZIO_CRYPT_OFF and manually add that
4619 	 * to the received properties.
4620 	 */
4621 	if (stream_wantsnewfs && !raw && rcvprops != NULL &&
4622 	    !nvlist_exists(cmdprops, zfs_prop_to_name(ZFS_PROP_ENCRYPTION))) {
4623 		if (oxprops == NULL)
4624 			oxprops = fnvlist_alloc();
4625 		fnvlist_add_uint64(oxprops,
4626 		    zfs_prop_to_name(ZFS_PROP_ENCRYPTION), ZIO_CRYPT_OFF);
4627 	}
4628 
4629 	if (flags->dryrun) {
4630 		void *buf = zfs_alloc(hdl, SPA_MAXBLOCKSIZE);
4631 
4632 		/*
4633 		 * We have read the DRR_BEGIN record, but we have
4634 		 * not yet read the payload. For non-dryrun sends
4635 		 * this will be done by the kernel, so we must
4636 		 * emulate that here, before attempting to read
4637 		 * more records.
4638 		 */
4639 		err = recv_read(hdl, infd, buf, drr->drr_payloadlen,
4640 		    flags->byteswap, NULL);
4641 		free(buf);
4642 		if (err != 0)
4643 			goto out;
4644 
4645 		err = recv_skip(hdl, infd, flags->byteswap);
4646 		goto out;
4647 	}
4648 
4649 	err = ioctl_err = lzc_receive_with_cmdprops(destsnap, rcvprops,
4650 	    oxprops, wkeydata, wkeylen, origin, flags->force, flags->resumable,
4651 	    raw, infd, drr_noswap, -1, &read_bytes, &errflags,
4652 	    NULL, &prop_errors);
4653 	ioctl_errno = ioctl_err;
4654 	prop_errflags = errflags;
4655 
4656 	if (err == 0) {
4657 		nvpair_t *prop_err = NULL;
4658 
4659 		while ((prop_err = nvlist_next_nvpair(prop_errors,
4660 		    prop_err)) != NULL) {
4661 			char tbuf[1024];
4662 			zfs_prop_t prop;
4663 			int intval;
4664 
4665 			prop = zfs_name_to_prop(nvpair_name(prop_err));
4666 			(void) nvpair_value_int32(prop_err, &intval);
4667 			if (strcmp(nvpair_name(prop_err),
4668 			    ZPROP_N_MORE_ERRORS) == 0) {
4669 				trunc_prop_errs(intval);
4670 				break;
4671 			} else if (snapname == NULL || finalsnap == NULL ||
4672 			    strcmp(finalsnap, snapname) == 0 ||
4673 			    strcmp(nvpair_name(prop_err),
4674 			    zfs_prop_to_name(ZFS_PROP_REFQUOTA)) != 0) {
4675 				/*
4676 				 * Skip the special case of, for example,
4677 				 * "refquota", errors on intermediate
4678 				 * snapshots leading up to a final one.
4679 				 * That's why we have all of the checks above.
4680 				 *
4681 				 * See zfs_ioctl.c's extract_delay_props() for
4682 				 * a list of props which can fail on
4683 				 * intermediate snapshots, but shouldn't
4684 				 * affect the overall receive.
4685 				 */
4686 				(void) snprintf(tbuf, sizeof (tbuf),
4687 				    dgettext(TEXT_DOMAIN,
4688 				    "cannot receive %s property on %s"),
4689 				    nvpair_name(prop_err), name);
4690 				zfs_setprop_error(hdl, prop, intval, tbuf);
4691 			}
4692 		}
4693 	}
4694 
4695 	if (err == 0 && snapprops_nvlist) {
4696 		zfs_cmd_t zc = {"\0"};
4697 
4698 		(void) strcpy(zc.zc_name, destsnap);
4699 		zc.zc_cookie = B_TRUE; /* received */
4700 		if (zcmd_write_src_nvlist(hdl, &zc, snapprops_nvlist) == 0) {
4701 			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
4702 			zcmd_free_nvlists(&zc);
4703 		}
4704 	}
4705 	if (err == 0 && snapholds_nvlist) {
4706 		nvpair_t *pair;
4707 		nvlist_t *holds, *errors = NULL;
4708 		int cleanup_fd = -1;
4709 
4710 		VERIFY(0 == nvlist_alloc(&holds, 0, KM_SLEEP));
4711 		for (pair = nvlist_next_nvpair(snapholds_nvlist, NULL);
4712 		    pair != NULL;
4713 		    pair = nvlist_next_nvpair(snapholds_nvlist, pair)) {
4714 			fnvlist_add_string(holds, destsnap, nvpair_name(pair));
4715 		}
4716 		(void) lzc_hold(holds, cleanup_fd, &errors);
4717 		fnvlist_free(snapholds_nvlist);
4718 		fnvlist_free(holds);
4719 	}
4720 
4721 	if (err && (ioctl_errno == ENOENT || ioctl_errno == EEXIST)) {
4722 		/*
4723 		 * It may be that this snapshot already exists,
4724 		 * in which case we want to consume & ignore it
4725 		 * rather than failing.
4726 		 */
4727 		avl_tree_t *local_avl;
4728 		nvlist_t *local_nv, *fs;
4729 		cp = strchr(destsnap, '@');
4730 
4731 		/*
4732 		 * XXX Do this faster by just iterating over snaps in
4733 		 * this fs.  Also if zc_value does not exist, we will
4734 		 * get a strange "does not exist" error message.
4735 		 */
4736 		*cp = '\0';
4737 		if (gather_nvlist(hdl, destsnap, NULL, NULL, B_FALSE, B_TRUE,
4738 		    B_FALSE, B_FALSE, B_FALSE, B_FALSE, B_FALSE, B_FALSE,
4739 		    B_TRUE, &local_nv, &local_avl) == 0) {
4740 			*cp = '@';
4741 			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
4742 			fsavl_destroy(local_avl);
4743 			fnvlist_free(local_nv);
4744 
4745 			if (fs != NULL) {
4746 				if (flags->verbose) {
4747 					(void) printf("snap %s already exists; "
4748 					    "ignoring\n", destsnap);
4749 				}
4750 				err = ioctl_err = recv_skip(hdl, infd,
4751 				    flags->byteswap);
4752 			}
4753 		}
4754 		*cp = '@';
4755 	}
4756 
4757 	if (ioctl_err != 0) {
4758 		switch (ioctl_errno) {
4759 		case ENODEV:
4760 			cp = strchr(destsnap, '@');
4761 			*cp = '\0';
4762 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4763 			    "most recent snapshot of %s does not\n"
4764 			    "match incremental source"), destsnap);
4765 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
4766 			*cp = '@';
4767 			break;
4768 		case ETXTBSY:
4769 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4770 			    "destination %s has been modified\n"
4771 			    "since most recent snapshot"), name);
4772 			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
4773 			break;
4774 		case EACCES:
4775 			if (raw && stream_wantsnewfs) {
4776 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4777 				    "failed to create encryption key"));
4778 			} else if (raw && !stream_wantsnewfs) {
4779 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4780 				    "encryption key does not match "
4781 				    "existing key"));
4782 			} else {
4783 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4784 				    "inherited key must be loaded"));
4785 			}
4786 			(void) zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
4787 			break;
4788 		case EEXIST:
4789 			cp = strchr(destsnap, '@');
4790 			if (newfs) {
4791 				/* it's the containing fs that exists */
4792 				*cp = '\0';
4793 			}
4794 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4795 			    "destination already exists"));
4796 			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
4797 			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
4798 			    destsnap);
4799 			*cp = '@';
4800 			break;
4801 		case EINVAL:
4802 			if (flags->resumable) {
4803 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4804 				    "kernel modules must be upgraded to "
4805 				    "receive this stream."));
4806 			} else if (embedded && !raw) {
4807 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4808 				    "incompatible embedded data stream "
4809 				    "feature with encrypted receive."));
4810 			}
4811 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4812 			break;
4813 		case ECKSUM:
4814 		case ZFS_ERR_STREAM_TRUNCATED:
4815 			recv_ecksum_set_aux(hdl, destsnap, flags->resumable,
4816 			    ioctl_err == ECKSUM);
4817 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4818 			break;
4819 		case ZFS_ERR_STREAM_LARGE_BLOCK_MISMATCH:
4820 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4821 			    "incremental send stream requires -L "
4822 			    "(--large-block), to match previous receive."));
4823 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4824 			break;
4825 		case ENOTSUP:
4826 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4827 			    "pool must be upgraded to receive this stream."));
4828 			(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
4829 			break;
4830 		case EDQUOT:
4831 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4832 			    "destination %s space quota exceeded."), name);
4833 			(void) zfs_error(hdl, EZFS_NOSPC, errbuf);
4834 			break;
4835 		case ZFS_ERR_FROM_IVSET_GUID_MISSING:
4836 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4837 			    "IV set guid missing. See errata %u at "
4838 			    "https://openzfs.github.io/openzfs-docs/msg/"
4839 			    "ZFS-8000-ER."),
4840 			    ZPOOL_ERRATA_ZOL_8308_ENCRYPTION);
4841 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4842 			break;
4843 		case ZFS_ERR_FROM_IVSET_GUID_MISMATCH:
4844 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4845 			    "IV set guid mismatch. See the 'zfs receive' "
4846 			    "man page section\n discussing the limitations "
4847 			    "of raw encrypted send streams."));
4848 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4849 			break;
4850 		case ZFS_ERR_SPILL_BLOCK_FLAG_MISSING:
4851 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4852 			    "Spill block flag missing for raw send.\n"
4853 			    "The zfs software on the sending system must "
4854 			    "be updated."));
4855 			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
4856 			break;
4857 		case EBUSY:
4858 			if (hastoken) {
4859 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4860 				    "destination %s contains "
4861 				    "partially-complete state from "
4862 				    "\"zfs receive -s\"."), name);
4863 				(void) zfs_error(hdl, EZFS_BUSY, errbuf);
4864 				break;
4865 			}
4866 			/* fallthru */
4867 		default:
4868 			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
4869 		}
4870 	}
4871 
4872 	/*
4873 	 * Mount the target filesystem (if created).  Also mount any
4874 	 * children of the target filesystem if we did a replication
4875 	 * receive (indicated by stream_avl being non-NULL).
4876 	 */
4877 	if (clp) {
4878 		if (!flags->nomount)
4879 			err |= changelist_postfix(clp);
4880 		changelist_free(clp);
4881 	}
4882 
4883 	if ((newfs || stream_avl) && type == ZFS_TYPE_FILESYSTEM && !redacted)
4884 		flags->domount = B_TRUE;
4885 
4886 	if (prop_errflags & ZPROP_ERR_NOCLEAR) {
4887 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
4888 		    "failed to clear unreceived properties on %s"), name);
4889 		(void) fprintf(stderr, "\n");
4890 	}
4891 	if (prop_errflags & ZPROP_ERR_NORESTORE) {
4892 		(void) fprintf(stderr, dgettext(TEXT_DOMAIN, "Warning: "
4893 		    "failed to restore original properties on %s"), name);
4894 		(void) fprintf(stderr, "\n");
4895 	}
4896 
4897 	if (err || ioctl_err) {
4898 		err = -1;
4899 		goto out;
4900 	}
4901 
4902 	if (flags->verbose) {
4903 		char buf1[64];
4904 		char buf2[64];
4905 		uint64_t bytes = read_bytes;
4906 		time_t delta = time(NULL) - begin_time;
4907 		if (delta == 0)
4908 			delta = 1;
4909 		zfs_nicebytes(bytes, buf1, sizeof (buf1));
4910 		zfs_nicebytes(bytes/delta, buf2, sizeof (buf1));
4911 
4912 		(void) printf("received %s stream in %lld seconds (%s/sec)\n",
4913 		    buf1, (longlong_t)delta, buf2);
4914 	}
4915 
4916 	err = 0;
4917 out:
4918 	if (prop_errors != NULL)
4919 		fnvlist_free(prop_errors);
4920 
4921 	if (tmp_keylocation[0] != '\0') {
4922 		fnvlist_add_string(rcvprops,
4923 		    zfs_prop_to_name(ZFS_PROP_KEYLOCATION), tmp_keylocation);
4924 	}
4925 
4926 	if (newprops)
4927 		fnvlist_free(rcvprops);
4928 
4929 	fnvlist_free(oxprops);
4930 	fnvlist_free(origprops);
4931 
4932 	return (err);
4933 }
4934 
4935 /*
4936  * Check properties we were asked to override (both -o|-x)
4937  */
4938 static boolean_t
4939 zfs_receive_checkprops(libzfs_handle_t *hdl, nvlist_t *props,
4940     const char *errbuf)
4941 {
4942 	nvpair_t *nvp;
4943 	zfs_prop_t prop;
4944 	const char *name;
4945 
4946 	nvp = NULL;
4947 	while ((nvp = nvlist_next_nvpair(props, nvp)) != NULL) {
4948 		name = nvpair_name(nvp);
4949 		prop = zfs_name_to_prop(name);
4950 
4951 		if (prop == ZPROP_INVAL) {
4952 			if (!zfs_prop_user(name)) {
4953 				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4954 				    "invalid property '%s'"), name);
4955 				return (B_FALSE);
4956 			}
4957 			continue;
4958 		}
4959 		/*
4960 		 * "origin" is readonly but is used to receive datasets as
4961 		 * clones so we don't raise an error here
4962 		 */
4963 		if (prop == ZFS_PROP_ORIGIN)
4964 			continue;
4965 
4966 		/* encryption params have their own verification later */
4967 		if (prop == ZFS_PROP_ENCRYPTION ||
4968 		    zfs_prop_encryption_key_param(prop))
4969 			continue;
4970 
4971 		/*
4972 		 * cannot override readonly, set-once and other specific
4973 		 * settable properties
4974 		 */
4975 		if (zfs_prop_readonly(prop) || prop == ZFS_PROP_VERSION ||
4976 		    prop == ZFS_PROP_VOLSIZE) {
4977 			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
4978 			    "invalid property '%s'"), name);
4979 			return (B_FALSE);
4980 		}
4981 	}
4982 
4983 	return (B_TRUE);
4984 }
4985 
4986 static int
4987 zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap,
4988     const char *originsnap, recvflags_t *flags, int infd, const char *sendfs,
4989     nvlist_t *stream_nv, avl_tree_t *stream_avl, char **top_zfs,
4990     const char *finalsnap, nvlist_t *cmdprops)
4991 {
4992 	int err;
4993 	dmu_replay_record_t drr, drr_noswap;
4994 	struct drr_begin *drrb = &drr.drr_u.drr_begin;
4995 	char errbuf[1024];
4996 	zio_cksum_t zcksum = { { 0 } };
4997 	uint64_t featureflags;
4998 	int hdrtype;
4999 
5000 	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
5001 	    "cannot receive"));
5002 
5003 	/* check cmdline props, raise an error if they cannot be received */
5004 	if (!zfs_receive_checkprops(hdl, cmdprops, errbuf)) {
5005 		return (zfs_error(hdl, EZFS_BADPROP, errbuf));
5006 	}
5007 
5008 	if (flags->isprefix &&
5009 	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
5010 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
5011 		    "(%s) does not exist"), tosnap);
5012 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
5013 	}
5014 	if (originsnap &&
5015 	    !zfs_dataset_exists(hdl, originsnap, ZFS_TYPE_DATASET)) {
5016 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified origin fs "
5017 		    "(%s) does not exist"), originsnap);
5018 		return (zfs_error(hdl, EZFS_NOENT, errbuf));
5019 	}
5020 
5021 	/* read in the BEGIN record */
5022 	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
5023 	    &zcksum)))
5024 		return (err);
5025 
5026 	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
5027 		/* It's the double end record at the end of a package */
5028 		return (ENODATA);
5029 	}
5030 
5031 	/* the kernel needs the non-byteswapped begin record */
5032 	drr_noswap = drr;
5033 
5034 	flags->byteswap = B_FALSE;
5035 	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
5036 		/*
5037 		 * We computed the checksum in the wrong byteorder in
5038 		 * recv_read() above; do it again correctly.
5039 		 */
5040 		bzero(&zcksum, sizeof (zio_cksum_t));
5041 		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
5042 		flags->byteswap = B_TRUE;
5043 
5044 		drr.drr_type = BSWAP_32(drr.drr_type);
5045 		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
5046 		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
5047 		drrb->drr_versioninfo = BSWAP_64(drrb->drr_versioninfo);
5048 		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
5049 		drrb->drr_type = BSWAP_32(drrb->drr_type);
5050 		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
5051 		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
5052 		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
5053 	}
5054 
5055 	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
5056 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
5057 		    "stream (bad magic number)"));
5058 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
5059 	}
5060 
5061 	featureflags = DMU_GET_FEATUREFLAGS(drrb->drr_versioninfo);
5062 	hdrtype = DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo);
5063 
5064 	if (!DMU_STREAM_SUPPORTED(featureflags) ||
5065 	    (hdrtype != DMU_SUBSTREAM && hdrtype != DMU_COMPOUNDSTREAM)) {
5066 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
5067 		    "stream has unsupported feature, feature flags = %llx"),
5068 		    (unsigned long long)featureflags);
5069 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
5070 	}
5071 
5072 	/* Holds feature is set once in the compound stream header. */
5073 	if (featureflags & DMU_BACKUP_FEATURE_HOLDS)
5074 		flags->holds = B_TRUE;
5075 
5076 	if (strchr(drrb->drr_toname, '@') == NULL) {
5077 		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
5078 		    "stream (bad snapshot name)"));
5079 		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
5080 	}
5081 
5082 	if (DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) == DMU_SUBSTREAM) {
5083 		char nonpackage_sendfs[ZFS_MAX_DATASET_NAME_LEN];
5084 		if (sendfs == NULL) {
5085 			/*
5086 			 * We were not called from zfs_receive_package(). Get
5087 			 * the fs specified by 'zfs send'.
5088 			 */
5089 			char *cp;
5090 			(void) strlcpy(nonpackage_sendfs,
5091 			    drr.drr_u.drr_begin.drr_toname,
5092 			    sizeof (nonpackage_sendfs));
5093 			if ((cp = strchr(nonpackage_sendfs, '@')) != NULL)
5094 				*cp = '\0';
5095 			sendfs = nonpackage_sendfs;
5096 			VERIFY(finalsnap == NULL);
5097 		}
5098 		return (zfs_receive_one(hdl, infd, tosnap, originsnap, flags,
5099 		    &drr, &drr_noswap, sendfs, stream_nv, stream_avl, top_zfs,
5100 		    finalsnap, cmdprops));
5101 	} else {
5102 		assert(DMU_GET_STREAM_HDRTYPE(drrb->drr_versioninfo) ==
5103 		    DMU_COMPOUNDSTREAM);
5104 		return (zfs_receive_package(hdl, infd, tosnap, flags, &drr,
5105 		    &zcksum, top_zfs, cmdprops));
5106 	}
5107 }
5108 
5109 /*
5110  * Restores a backup of tosnap from the file descriptor specified by infd.
5111  * Return 0 on total success, -2 if some things couldn't be
5112  * destroyed/renamed/promoted, -1 if some things couldn't be received.
5113  * (-1 will override -2, if -1 and the resumable flag was specified the
5114  * transfer can be resumed if the sending side supports it).
5115  */
5116 int
5117 zfs_receive(libzfs_handle_t *hdl, const char *tosnap, nvlist_t *props,
5118     recvflags_t *flags, int infd, avl_tree_t *stream_avl)
5119 {
5120 	char *top_zfs = NULL;
5121 	int err;
5122 	struct stat sb;
5123 	char *originsnap = NULL;
5124 
5125 	/*
5126 	 * The only way fstat can fail is if we do not have a valid file
5127 	 * descriptor.
5128 	 */
5129 	if (fstat(infd, &sb) == -1) {
5130 		perror("fstat");
5131 		return (-2);
5132 	}
5133 
5134 	/*
5135 	 * It is not uncommon for gigabytes to be processed in zfs receive.
5136 	 * Speculatively increase the buffer size if supported by the platform.
5137 	 */
5138 	if (S_ISFIFO(sb.st_mode))
5139 		libzfs_set_pipe_max(infd);
5140 
5141 	if (props) {
5142 		err = nvlist_lookup_string(props, "origin", &originsnap);
5143 		if (err && err != ENOENT)
5144 			return (err);
5145 	}
5146 
5147 	err = zfs_receive_impl(hdl, tosnap, originsnap, flags, infd, NULL, NULL,
5148 	    stream_avl, &top_zfs, NULL, props);
5149 
5150 	if (err == 0 && !flags->nomount && flags->domount && top_zfs) {
5151 		zfs_handle_t *zhp = NULL;
5152 		prop_changelist_t *clp = NULL;
5153 
5154 		zhp = zfs_open(hdl, top_zfs,
5155 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
5156 		if (zhp == NULL) {
5157 			err = -1;
5158 			goto out;
5159 		} else {
5160 			if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
5161 				zfs_close(zhp);
5162 				goto out;
5163 			}
5164 
5165 			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
5166 			    CL_GATHER_MOUNT_ALWAYS,
5167 			    flags->forceunmount ? MS_FORCE : 0);
5168 			zfs_close(zhp);
5169 			if (clp == NULL) {
5170 				err = -1;
5171 				goto out;
5172 			}
5173 
5174 			/* mount and share received datasets */
5175 			err = changelist_postfix(clp);
5176 			changelist_free(clp);
5177 			if (err != 0)
5178 				err = -1;
5179 		}
5180 	}
5181 
5182 out:
5183 	if (top_zfs)
5184 		free(top_zfs);
5185 
5186 	return (err);
5187 }
5188