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