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