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