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