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