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