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