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