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