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