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