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