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