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