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