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