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