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