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