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