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