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