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