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