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