libzfs_sendrecv.c revision 10299:80845694147f
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 2009 Sun Microsystems, Inc.  All rights reserved.
24 * Use is subject to license terms.
25 */
26
27#include <assert.h>
28#include <ctype.h>
29#include <errno.h>
30#include <libdevinfo.h>
31#include <libintl.h>
32#include <stdio.h>
33#include <stdlib.h>
34#include <strings.h>
35#include <unistd.h>
36#include <stddef.h>
37#include <fcntl.h>
38#include <sys/mount.h>
39#include <sys/mntent.h>
40#include <sys/mnttab.h>
41#include <sys/avl.h>
42#include <stddef.h>
43
44#include <libzfs.h>
45
46#include "zfs_namecheck.h"
47#include "zfs_prop.h"
48#include "libzfs_impl.h"
49
50#include <fletcher.c> /* XXX */
51
52static int zfs_receive_impl(libzfs_handle_t *, const char *, recvflags_t,
53    int, avl_tree_t *, char **);
54
55/*
56 * Routines for dealing with the AVL tree of fs-nvlists
57 */
58typedef struct fsavl_node {
59	avl_node_t fn_node;
60	nvlist_t *fn_nvfs;
61	char *fn_snapname;
62	uint64_t fn_guid;
63} fsavl_node_t;
64
65static int
66fsavl_compare(const void *arg1, const void *arg2)
67{
68	const fsavl_node_t *fn1 = arg1;
69	const fsavl_node_t *fn2 = arg2;
70
71	if (fn1->fn_guid > fn2->fn_guid)
72		return (+1);
73	else if (fn1->fn_guid < fn2->fn_guid)
74		return (-1);
75	else
76		return (0);
77}
78
79/*
80 * Given the GUID of a snapshot, find its containing filesystem and
81 * (optionally) name.
82 */
83static nvlist_t *
84fsavl_find(avl_tree_t *avl, uint64_t snapguid, char **snapname)
85{
86	fsavl_node_t fn_find;
87	fsavl_node_t *fn;
88
89	fn_find.fn_guid = snapguid;
90
91	fn = avl_find(avl, &fn_find, NULL);
92	if (fn) {
93		if (snapname)
94			*snapname = fn->fn_snapname;
95		return (fn->fn_nvfs);
96	}
97	return (NULL);
98}
99
100static void
101fsavl_destroy(avl_tree_t *avl)
102{
103	fsavl_node_t *fn;
104	void *cookie;
105
106	if (avl == NULL)
107		return;
108
109	cookie = NULL;
110	while ((fn = avl_destroy_nodes(avl, &cookie)) != NULL)
111		free(fn);
112	avl_destroy(avl);
113	free(avl);
114}
115
116/*
117 * Given an nvlist, produce an avl tree of snapshots, ordered by guid
118 */
119static avl_tree_t *
120fsavl_create(nvlist_t *fss)
121{
122	avl_tree_t *fsavl;
123	nvpair_t *fselem = NULL;
124
125	if ((fsavl = malloc(sizeof (avl_tree_t))) == NULL)
126		return (NULL);
127
128	avl_create(fsavl, fsavl_compare, sizeof (fsavl_node_t),
129	    offsetof(fsavl_node_t, fn_node));
130
131	while ((fselem = nvlist_next_nvpair(fss, fselem)) != NULL) {
132		nvlist_t *nvfs, *snaps;
133		nvpair_t *snapelem = NULL;
134
135		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
136		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
137
138		while ((snapelem =
139		    nvlist_next_nvpair(snaps, snapelem)) != NULL) {
140			fsavl_node_t *fn;
141			uint64_t guid;
142
143			VERIFY(0 == nvpair_value_uint64(snapelem, &guid));
144			if ((fn = malloc(sizeof (fsavl_node_t))) == NULL) {
145				fsavl_destroy(fsavl);
146				return (NULL);
147			}
148			fn->fn_nvfs = nvfs;
149			fn->fn_snapname = nvpair_name(snapelem);
150			fn->fn_guid = guid;
151
152			/*
153			 * Note: if there are multiple snaps with the
154			 * same GUID, we ignore all but one.
155			 */
156			if (avl_find(fsavl, fn, NULL) == NULL)
157				avl_add(fsavl, fn);
158			else
159				free(fn);
160		}
161	}
162
163	return (fsavl);
164}
165
166/*
167 * Routines for dealing with the giant nvlist of fs-nvlists, etc.
168 */
169typedef struct send_data {
170	uint64_t parent_fromsnap_guid;
171	nvlist_t *parent_snaps;
172	nvlist_t *fss;
173	nvlist_t *snapprops;
174	const char *fromsnap;
175	const char *tosnap;
176
177	/*
178	 * The header nvlist is of the following format:
179	 * {
180	 *   "tosnap" -> string
181	 *   "fromsnap" -> string (if incremental)
182	 *   "fss" -> {
183	 *	id -> {
184	 *
185	 *	 "name" -> string (full name; for debugging)
186	 *	 "parentfromsnap" -> number (guid of fromsnap in parent)
187	 *
188	 *	 "props" -> { name -> value (only if set here) }
189	 *	 "snaps" -> { name (lastname) -> number (guid) }
190	 *	 "snapprops" -> { name (lastname) -> { name -> value } }
191	 *
192	 *	 "origin" -> number (guid) (if clone)
193	 *	 "sent" -> boolean (not on-disk)
194	 *	}
195	 *   }
196	 * }
197	 *
198	 */
199} send_data_t;
200
201static void send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv);
202
203static int
204send_iterate_snap(zfs_handle_t *zhp, void *arg)
205{
206	send_data_t *sd = arg;
207	uint64_t guid = zhp->zfs_dmustats.dds_guid;
208	char *snapname;
209	nvlist_t *nv;
210
211	snapname = strrchr(zhp->zfs_name, '@')+1;
212
213	VERIFY(0 == nvlist_add_uint64(sd->parent_snaps, snapname, guid));
214	/*
215	 * NB: if there is no fromsnap here (it's a newly created fs in
216	 * an incremental replication), we will substitute the tosnap.
217	 */
218	if ((sd->fromsnap && strcmp(snapname, sd->fromsnap) == 0) ||
219	    (sd->parent_fromsnap_guid == 0 && sd->tosnap &&
220	    strcmp(snapname, sd->tosnap) == 0)) {
221		sd->parent_fromsnap_guid = guid;
222	}
223
224	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
225	send_iterate_prop(zhp, nv);
226	VERIFY(0 == nvlist_add_nvlist(sd->snapprops, snapname, nv));
227	nvlist_free(nv);
228
229	zfs_close(zhp);
230	return (0);
231}
232
233static void
234send_iterate_prop(zfs_handle_t *zhp, nvlist_t *nv)
235{
236	nvpair_t *elem = NULL;
237
238	while ((elem = nvlist_next_nvpair(zhp->zfs_props, elem)) != NULL) {
239		char *propname = nvpair_name(elem);
240		zfs_prop_t prop = zfs_name_to_prop(propname);
241		nvlist_t *propnv;
242
243		assert(zfs_prop_user(propname) || prop != ZPROP_INVAL);
244
245		if (!zfs_prop_user(propname) && zfs_prop_readonly(prop))
246			continue;
247
248		verify(nvpair_value_nvlist(elem, &propnv) == 0);
249		if (prop == ZFS_PROP_QUOTA || prop == ZFS_PROP_RESERVATION ||
250		    prop == ZFS_PROP_REFQUOTA ||
251		    prop == ZFS_PROP_REFRESERVATION) {
252			/* these guys are modifyable, but have no source */
253			uint64_t value;
254			verify(nvlist_lookup_uint64(propnv,
255			    ZPROP_VALUE, &value) == 0);
256			if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT)
257				continue;
258		} else {
259			char *source;
260			if (nvlist_lookup_string(propnv,
261			    ZPROP_SOURCE, &source) != 0)
262				continue;
263			if (strcmp(source, zhp->zfs_name) != 0)
264				continue;
265		}
266
267		if (zfs_prop_user(propname) ||
268		    zfs_prop_get_type(prop) == PROP_TYPE_STRING) {
269			char *value;
270			verify(nvlist_lookup_string(propnv,
271			    ZPROP_VALUE, &value) == 0);
272			VERIFY(0 == nvlist_add_string(nv, propname, value));
273		} else {
274			uint64_t value;
275			verify(nvlist_lookup_uint64(propnv,
276			    ZPROP_VALUE, &value) == 0);
277			VERIFY(0 == nvlist_add_uint64(nv, propname, value));
278		}
279	}
280}
281
282/*
283 * recursively generate nvlists describing datasets.  See comment
284 * for the data structure send_data_t above for description of contents
285 * of the nvlist.
286 */
287static int
288send_iterate_fs(zfs_handle_t *zhp, void *arg)
289{
290	send_data_t *sd = arg;
291	nvlist_t *nvfs, *nv;
292	int rv;
293	uint64_t parent_fromsnap_guid_save = sd->parent_fromsnap_guid;
294	uint64_t guid = zhp->zfs_dmustats.dds_guid;
295	char guidstring[64];
296
297	VERIFY(0 == nvlist_alloc(&nvfs, NV_UNIQUE_NAME, 0));
298	VERIFY(0 == nvlist_add_string(nvfs, "name", zhp->zfs_name));
299	VERIFY(0 == nvlist_add_uint64(nvfs, "parentfromsnap",
300	    sd->parent_fromsnap_guid));
301
302	if (zhp->zfs_dmustats.dds_origin[0]) {
303		zfs_handle_t *origin = zfs_open(zhp->zfs_hdl,
304		    zhp->zfs_dmustats.dds_origin, ZFS_TYPE_SNAPSHOT);
305		if (origin == NULL)
306			return (-1);
307		VERIFY(0 == nvlist_add_uint64(nvfs, "origin",
308		    origin->zfs_dmustats.dds_guid));
309	}
310
311	/* iterate over props */
312	VERIFY(0 == nvlist_alloc(&nv, NV_UNIQUE_NAME, 0));
313	send_iterate_prop(zhp, nv);
314	VERIFY(0 == nvlist_add_nvlist(nvfs, "props", nv));
315	nvlist_free(nv);
316
317	/* iterate over snaps, and set sd->parent_fromsnap_guid */
318	sd->parent_fromsnap_guid = 0;
319	VERIFY(0 == nvlist_alloc(&sd->parent_snaps, NV_UNIQUE_NAME, 0));
320	VERIFY(0 == nvlist_alloc(&sd->snapprops, NV_UNIQUE_NAME, 0));
321	(void) zfs_iter_snapshots(zhp, send_iterate_snap, sd);
322	VERIFY(0 == nvlist_add_nvlist(nvfs, "snaps", sd->parent_snaps));
323	VERIFY(0 == nvlist_add_nvlist(nvfs, "snapprops", sd->snapprops));
324	nvlist_free(sd->parent_snaps);
325	nvlist_free(sd->snapprops);
326
327	/* add this fs to nvlist */
328	(void) snprintf(guidstring, sizeof (guidstring),
329	    "0x%llx", (longlong_t)guid);
330	VERIFY(0 == nvlist_add_nvlist(sd->fss, guidstring, nvfs));
331	nvlist_free(nvfs);
332
333	/* iterate over children */
334	rv = zfs_iter_filesystems(zhp, send_iterate_fs, sd);
335
336	sd->parent_fromsnap_guid = parent_fromsnap_guid_save;
337
338	zfs_close(zhp);
339	return (rv);
340}
341
342static int
343gather_nvlist(libzfs_handle_t *hdl, const char *fsname, const char *fromsnap,
344    const char *tosnap, nvlist_t **nvlp, avl_tree_t **avlp)
345{
346	zfs_handle_t *zhp;
347	send_data_t sd = { 0 };
348	int error;
349
350	zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
351	if (zhp == NULL)
352		return (EZFS_BADTYPE);
353
354	VERIFY(0 == nvlist_alloc(&sd.fss, NV_UNIQUE_NAME, 0));
355	sd.fromsnap = fromsnap;
356	sd.tosnap = tosnap;
357
358	if ((error = send_iterate_fs(zhp, &sd)) != 0) {
359		nvlist_free(sd.fss);
360		if (avlp != NULL)
361			*avlp = NULL;
362		*nvlp = NULL;
363		return (error);
364	}
365
366	if (avlp != NULL && (*avlp = fsavl_create(sd.fss)) == NULL) {
367		nvlist_free(sd.fss);
368		*nvlp = NULL;
369		return (EZFS_NOMEM);
370	}
371
372	*nvlp = sd.fss;
373	return (0);
374}
375
376/*
377 * Routines for dealing with the sorted snapshot functionality
378 */
379typedef struct zfs_node {
380	zfs_handle_t	*zn_handle;
381	avl_node_t	zn_avlnode;
382} zfs_node_t;
383
384static int
385zfs_sort_snaps(zfs_handle_t *zhp, void *data)
386{
387	avl_tree_t *avl = data;
388	zfs_node_t *node = zfs_alloc(zhp->zfs_hdl, sizeof (zfs_node_t));
389
390	node->zn_handle = zhp;
391	avl_add(avl, node);
392	return (0);
393}
394
395/* ARGSUSED */
396static int
397zfs_snapshot_compare(const void *larg, const void *rarg)
398{
399	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
400	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
401	uint64_t lcreate, rcreate;
402
403	/*
404	 * Sort them according to creation time.  We use the hidden
405	 * CREATETXG property to get an absolute ordering of snapshots.
406	 */
407	lcreate = zfs_prop_get_int(l, ZFS_PROP_CREATETXG);
408	rcreate = zfs_prop_get_int(r, ZFS_PROP_CREATETXG);
409
410	if (lcreate < rcreate)
411		return (-1);
412	else if (lcreate > rcreate)
413		return (+1);
414	else
415		return (0);
416}
417
418static int
419zfs_iter_snapshots_sorted(zfs_handle_t *zhp, zfs_iter_f callback, void *data)
420{
421	int ret = 0;
422	zfs_node_t *node;
423	avl_tree_t avl;
424	void *cookie = NULL;
425
426	avl_create(&avl, zfs_snapshot_compare,
427	    sizeof (zfs_node_t), offsetof(zfs_node_t, zn_avlnode));
428
429	ret = zfs_iter_snapshots(zhp, zfs_sort_snaps, &avl);
430
431	for (node = avl_first(&avl); node != NULL; node = AVL_NEXT(&avl, node))
432		ret |= callback(node->zn_handle, data);
433
434	while ((node = avl_destroy_nodes(&avl, &cookie)) != NULL)
435		free(node);
436
437	avl_destroy(&avl);
438
439	return (ret);
440}
441
442/*
443 * Routines specific to "zfs send"
444 */
445typedef struct send_dump_data {
446	/* these are all just the short snapname (the part after the @) */
447	const char *fromsnap;
448	const char *tosnap;
449	char lastsnap[ZFS_MAXNAMELEN];
450	boolean_t seenfrom, seento, replicate, doall, fromorigin;
451	boolean_t verbose;
452	int outfd;
453	boolean_t err;
454	nvlist_t *fss;
455	avl_tree_t *fsavl;
456} send_dump_data_t;
457
458/*
459 * Dumps a backup of the given snapshot (incremental from fromsnap if it's not
460 * NULL) to the file descriptor specified by outfd.
461 */
462static int
463dump_ioctl(zfs_handle_t *zhp, const char *fromsnap, boolean_t fromorigin,
464    int outfd)
465{
466	zfs_cmd_t zc = { 0 };
467	libzfs_handle_t *hdl = zhp->zfs_hdl;
468
469	assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
470	assert(fromsnap == NULL || fromsnap[0] == '\0' || !fromorigin);
471
472	(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
473	if (fromsnap)
474		(void) strlcpy(zc.zc_value, fromsnap, sizeof (zc.zc_value));
475	zc.zc_cookie = outfd;
476	zc.zc_obj = fromorigin;
477
478	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SEND, &zc) != 0) {
479		char errbuf[1024];
480		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
481		    "warning: cannot send '%s'"), zhp->zfs_name);
482
483		switch (errno) {
484
485		case EXDEV:
486			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
487			    "not an earlier snapshot from the same fs"));
488			return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
489
490		case ENOENT:
491			if (zfs_dataset_exists(hdl, zc.zc_name,
492			    ZFS_TYPE_SNAPSHOT)) {
493				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
494				    "incremental source (@%s) does not exist"),
495				    zc.zc_value);
496			}
497			return (zfs_error(hdl, EZFS_NOENT, errbuf));
498
499		case EDQUOT:
500		case EFBIG:
501		case EIO:
502		case ENOLINK:
503		case ENOSPC:
504		case ENOSTR:
505		case ENXIO:
506		case EPIPE:
507		case ERANGE:
508		case EFAULT:
509		case EROFS:
510			zfs_error_aux(hdl, strerror(errno));
511			return (zfs_error(hdl, EZFS_BADBACKUP, errbuf));
512
513		default:
514			return (zfs_standard_error(hdl, errno, errbuf));
515		}
516	}
517
518	return (0);
519}
520
521static int
522dump_snapshot(zfs_handle_t *zhp, void *arg)
523{
524	send_dump_data_t *sdd = arg;
525	const char *thissnap;
526	int err;
527
528	thissnap = strchr(zhp->zfs_name, '@') + 1;
529
530	if (sdd->fromsnap && !sdd->seenfrom &&
531	    strcmp(sdd->fromsnap, thissnap) == 0) {
532		sdd->seenfrom = B_TRUE;
533		(void) strcpy(sdd->lastsnap, thissnap);
534		zfs_close(zhp);
535		return (0);
536	}
537
538	if (sdd->seento || !sdd->seenfrom) {
539		zfs_close(zhp);
540		return (0);
541	}
542
543	/* send it */
544	if (sdd->verbose) {
545		(void) fprintf(stderr, "sending from @%s to %s\n",
546		    sdd->lastsnap, zhp->zfs_name);
547	}
548
549	err = dump_ioctl(zhp, sdd->lastsnap,
550	    sdd->lastsnap[0] == '\0' && (sdd->fromorigin || sdd->replicate),
551	    sdd->outfd);
552
553	if (!sdd->seento && strcmp(sdd->tosnap, thissnap) == 0)
554		sdd->seento = B_TRUE;
555
556	(void) strcpy(sdd->lastsnap, thissnap);
557	zfs_close(zhp);
558	return (err);
559}
560
561static int
562dump_filesystem(zfs_handle_t *zhp, void *arg)
563{
564	int rv = 0;
565	send_dump_data_t *sdd = arg;
566	boolean_t missingfrom = B_FALSE;
567	zfs_cmd_t zc = { 0 };
568
569	(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
570	    zhp->zfs_name, sdd->tosnap);
571	if (ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0) {
572		(void) fprintf(stderr, "WARNING: "
573		    "could not send %s@%s: does not exist\n",
574		    zhp->zfs_name, sdd->tosnap);
575		sdd->err = B_TRUE;
576		return (0);
577	}
578
579	if (sdd->replicate && sdd->fromsnap) {
580		/*
581		 * If this fs does not have fromsnap, and we're doing
582		 * recursive, we need to send a full stream from the
583		 * beginning (or an incremental from the origin if this
584		 * is a clone).  If we're doing non-recursive, then let
585		 * them get the error.
586		 */
587		(void) snprintf(zc.zc_name, sizeof (zc.zc_name), "%s@%s",
588		    zhp->zfs_name, sdd->fromsnap);
589		if (ioctl(zhp->zfs_hdl->libzfs_fd,
590		    ZFS_IOC_OBJSET_STATS, &zc) != 0) {
591			missingfrom = B_TRUE;
592		}
593	}
594
595	if (sdd->doall) {
596		sdd->seenfrom = sdd->seento = sdd->lastsnap[0] = 0;
597		if (sdd->fromsnap == NULL || missingfrom)
598			sdd->seenfrom = B_TRUE;
599
600		rv = zfs_iter_snapshots_sorted(zhp, dump_snapshot, arg);
601		if (!sdd->seenfrom) {
602			(void) fprintf(stderr,
603			    "WARNING: could not send %s@%s:\n"
604			    "incremental source (%s@%s) does not exist\n",
605			    zhp->zfs_name, sdd->tosnap,
606			    zhp->zfs_name, sdd->fromsnap);
607			sdd->err = B_TRUE;
608		} else if (!sdd->seento) {
609			if (sdd->fromsnap) {
610				(void) fprintf(stderr,
611				    "WARNING: could not send %s@%s:\n"
612				    "incremental source (%s@%s) "
613				    "is not earlier than it\n",
614				    zhp->zfs_name, sdd->tosnap,
615				    zhp->zfs_name, sdd->fromsnap);
616			} else {
617				(void) fprintf(stderr, "WARNING: "
618				    "could not send %s@%s: does not exist\n",
619				    zhp->zfs_name, sdd->tosnap);
620			}
621			sdd->err = B_TRUE;
622		}
623	} else {
624		zfs_handle_t *snapzhp;
625		char snapname[ZFS_MAXNAMELEN];
626
627		(void) snprintf(snapname, sizeof (snapname), "%s@%s",
628		    zfs_get_name(zhp), sdd->tosnap);
629		snapzhp = zfs_open(zhp->zfs_hdl, snapname, ZFS_TYPE_SNAPSHOT);
630		if (snapzhp == NULL) {
631			rv = -1;
632		} else {
633			rv = dump_ioctl(snapzhp,
634			    missingfrom ? NULL : sdd->fromsnap,
635			    sdd->fromorigin || missingfrom,
636			    sdd->outfd);
637			sdd->seento = B_TRUE;
638			zfs_close(snapzhp);
639		}
640	}
641
642	return (rv);
643}
644
645static int
646dump_filesystems(zfs_handle_t *rzhp, void *arg)
647{
648	send_dump_data_t *sdd = arg;
649	nvpair_t *fspair;
650	boolean_t needagain, progress;
651
652	if (!sdd->replicate)
653		return (dump_filesystem(rzhp, sdd));
654
655again:
656	needagain = progress = B_FALSE;
657	for (fspair = nvlist_next_nvpair(sdd->fss, NULL); fspair;
658	    fspair = nvlist_next_nvpair(sdd->fss, fspair)) {
659		nvlist_t *fslist;
660		char *fsname;
661		zfs_handle_t *zhp;
662		int err;
663		uint64_t origin_guid = 0;
664		nvlist_t *origin_nv;
665
666		VERIFY(nvpair_value_nvlist(fspair, &fslist) == 0);
667		if (nvlist_lookup_boolean(fslist, "sent") == 0)
668			continue;
669
670		VERIFY(nvlist_lookup_string(fslist, "name", &fsname) == 0);
671		(void) nvlist_lookup_uint64(fslist, "origin", &origin_guid);
672
673		origin_nv = fsavl_find(sdd->fsavl, origin_guid, NULL);
674		if (origin_nv &&
675		    nvlist_lookup_boolean(origin_nv, "sent") == ENOENT) {
676			/*
677			 * origin has not been sent yet;
678			 * skip this clone.
679			 */
680			needagain = B_TRUE;
681			continue;
682		}
683
684		zhp = zfs_open(rzhp->zfs_hdl, fsname, ZFS_TYPE_DATASET);
685		if (zhp == NULL)
686			return (-1);
687		err = dump_filesystem(zhp, sdd);
688		VERIFY(nvlist_add_boolean(fslist, "sent") == 0);
689		progress = B_TRUE;
690		zfs_close(zhp);
691		if (err)
692			return (err);
693	}
694	if (needagain) {
695		assert(progress);
696		goto again;
697	}
698	return (0);
699}
700
701/*
702 * Generate a send stream for the dataset identified by the argument zhp.
703 *
704 * The content of the send stream is the snapshot identified by
705 * 'tosnap'.  Incremental streams are requested in two ways:
706 *     - from the snapshot identified by "fromsnap" (if non-null) or
707 *     - from the origin of the dataset identified by zhp, which must
708 *	 be a clone.  In this case, "fromsnap" is null and "fromorigin"
709 *	 is TRUE.
710 *
711 * The send stream is recursive (i.e. dumps a hierarchy of snapshots) and
712 * uses a special header (with a version field of DMU_BACKUP_HEADER_VERSION)
713 * if "replicate" is set.  If "doall" is set, dump all the intermediate
714 * snapshots. The DMU_BACKUP_HEADER_VERSION header is used in the "doall"
715 * case too.
716 */
717int
718zfs_send(zfs_handle_t *zhp, const char *fromsnap, const char *tosnap,
719    boolean_t replicate, boolean_t doall, boolean_t fromorigin,
720    boolean_t verbose, int outfd)
721{
722	char errbuf[1024];
723	send_dump_data_t sdd = { 0 };
724	int err;
725	nvlist_t *fss = NULL;
726	avl_tree_t *fsavl = NULL;
727
728	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
729	    "cannot send '%s'"), zhp->zfs_name);
730
731	if (fromsnap && fromsnap[0] == '\0') {
732		zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
733		    "zero-length incremental source"));
734		return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
735	}
736
737	if (replicate || doall) {
738		dmu_replay_record_t drr = { 0 };
739		char *packbuf = NULL;
740		size_t buflen = 0;
741		zio_cksum_t zc = { 0 };
742
743		assert(fromsnap || doall);
744
745		if (replicate) {
746			nvlist_t *hdrnv;
747
748			VERIFY(0 == nvlist_alloc(&hdrnv, NV_UNIQUE_NAME, 0));
749			if (fromsnap) {
750				VERIFY(0 == nvlist_add_string(hdrnv,
751				    "fromsnap", fromsnap));
752			}
753			VERIFY(0 == nvlist_add_string(hdrnv, "tosnap", tosnap));
754
755			err = gather_nvlist(zhp->zfs_hdl, zhp->zfs_name,
756			    fromsnap, tosnap, &fss, &fsavl);
757			if (err)
758				return (err);
759			VERIFY(0 == nvlist_add_nvlist(hdrnv, "fss", fss));
760			err = nvlist_pack(hdrnv, &packbuf, &buflen,
761			    NV_ENCODE_XDR, 0);
762			nvlist_free(hdrnv);
763			if (err) {
764				fsavl_destroy(fsavl);
765				nvlist_free(fss);
766				return (zfs_standard_error(zhp->zfs_hdl,
767				    err, errbuf));
768			}
769		}
770
771		/* write first begin record */
772		drr.drr_type = DRR_BEGIN;
773		drr.drr_u.drr_begin.drr_magic = DMU_BACKUP_MAGIC;
774		drr.drr_u.drr_begin.drr_version = DMU_BACKUP_HEADER_VERSION;
775		(void) snprintf(drr.drr_u.drr_begin.drr_toname,
776		    sizeof (drr.drr_u.drr_begin.drr_toname),
777		    "%s@%s", zhp->zfs_name, tosnap);
778		drr.drr_payloadlen = buflen;
779		fletcher_4_incremental_native(&drr, sizeof (drr), &zc);
780		err = write(outfd, &drr, sizeof (drr));
781
782		/* write header nvlist */
783		if (err != -1) {
784			fletcher_4_incremental_native(packbuf, buflen, &zc);
785			err = write(outfd, packbuf, buflen);
786		}
787		free(packbuf);
788		if (err == -1) {
789			fsavl_destroy(fsavl);
790			nvlist_free(fss);
791			return (zfs_standard_error(zhp->zfs_hdl,
792			    errno, errbuf));
793		}
794
795		/* write end record */
796		if (err != -1) {
797			bzero(&drr, sizeof (drr));
798			drr.drr_type = DRR_END;
799			drr.drr_u.drr_end.drr_checksum = zc;
800			err = write(outfd, &drr, sizeof (drr));
801			if (err == -1) {
802				fsavl_destroy(fsavl);
803				nvlist_free(fss);
804				return (zfs_standard_error(zhp->zfs_hdl,
805				    errno, errbuf));
806			}
807		}
808	}
809
810	/* dump each stream */
811	sdd.fromsnap = fromsnap;
812	sdd.tosnap = tosnap;
813	sdd.outfd = outfd;
814	sdd.replicate = replicate;
815	sdd.doall = doall;
816	sdd.fromorigin = fromorigin;
817	sdd.fss = fss;
818	sdd.fsavl = fsavl;
819	sdd.verbose = verbose;
820	err = dump_filesystems(zhp, &sdd);
821	fsavl_destroy(fsavl);
822	nvlist_free(fss);
823
824	if (replicate || doall) {
825		/*
826		 * write final end record.  NB: want to do this even if
827		 * there was some error, because it might not be totally
828		 * failed.
829		 */
830		dmu_replay_record_t drr = { 0 };
831		drr.drr_type = DRR_END;
832		if (write(outfd, &drr, sizeof (drr)) == -1) {
833			return (zfs_standard_error(zhp->zfs_hdl,
834			    errno, errbuf));
835		}
836	}
837
838	return (err || sdd.err);
839}
840
841/*
842 * Routines specific to "zfs recv"
843 */
844
845static int
846recv_read(libzfs_handle_t *hdl, int fd, void *buf, int ilen,
847    boolean_t byteswap, zio_cksum_t *zc)
848{
849	char *cp = buf;
850	int rv;
851	int len = ilen;
852
853	do {
854		rv = read(fd, cp, len);
855		cp += rv;
856		len -= rv;
857	} while (rv > 0);
858
859	if (rv < 0 || len != 0) {
860		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
861		    "failed to read from stream"));
862		return (zfs_error(hdl, EZFS_BADSTREAM, dgettext(TEXT_DOMAIN,
863		    "cannot receive")));
864	}
865
866	if (zc) {
867		if (byteswap)
868			fletcher_4_incremental_byteswap(buf, ilen, zc);
869		else
870			fletcher_4_incremental_native(buf, ilen, zc);
871	}
872	return (0);
873}
874
875static int
876recv_read_nvlist(libzfs_handle_t *hdl, int fd, int len, nvlist_t **nvp,
877    boolean_t byteswap, zio_cksum_t *zc)
878{
879	char *buf;
880	int err;
881
882	buf = zfs_alloc(hdl, len);
883	if (buf == NULL)
884		return (ENOMEM);
885
886	err = recv_read(hdl, fd, buf, len, byteswap, zc);
887	if (err != 0) {
888		free(buf);
889		return (err);
890	}
891
892	err = nvlist_unpack(buf, len, nvp, 0);
893	free(buf);
894	if (err != 0) {
895		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
896		    "stream (malformed nvlist)"));
897		return (EINVAL);
898	}
899	return (0);
900}
901
902static int
903recv_rename(libzfs_handle_t *hdl, const char *name, const char *tryname,
904    int baselen, char *newname, recvflags_t flags)
905{
906	static int seq;
907	zfs_cmd_t zc = { 0 };
908	int err;
909	prop_changelist_t *clp;
910	zfs_handle_t *zhp;
911
912	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
913	if (zhp == NULL)
914		return (-1);
915	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
916	    flags.force ? MS_FORCE : 0);
917	zfs_close(zhp);
918	if (clp == NULL)
919		return (-1);
920	err = changelist_prefix(clp);
921	if (err)
922		return (err);
923
924	zc.zc_objset_type = DMU_OST_ZFS;
925	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
926
927	if (tryname) {
928		(void) strcpy(newname, tryname);
929
930		(void) strlcpy(zc.zc_value, tryname, sizeof (zc.zc_value));
931
932		if (flags.verbose) {
933			(void) printf("attempting rename %s to %s\n",
934			    zc.zc_name, zc.zc_value);
935		}
936		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
937		if (err == 0)
938			changelist_rename(clp, name, tryname);
939	} else {
940		err = ENOENT;
941	}
942
943	if (err != 0 && strncmp(name+baselen, "recv-", 5) != 0) {
944		seq++;
945
946		(void) strncpy(newname, name, baselen);
947		(void) snprintf(newname+baselen, ZFS_MAXNAMELEN-baselen,
948		    "recv-%u-%u", getpid(), seq);
949		(void) strlcpy(zc.zc_value, newname, sizeof (zc.zc_value));
950
951		if (flags.verbose) {
952			(void) printf("failed - trying rename %s to %s\n",
953			    zc.zc_name, zc.zc_value);
954		}
955		err = ioctl(hdl->libzfs_fd, ZFS_IOC_RENAME, &zc);
956		if (err == 0)
957			changelist_rename(clp, name, newname);
958		if (err && flags.verbose) {
959			(void) printf("failed (%u) - "
960			    "will try again on next pass\n", errno);
961		}
962		err = EAGAIN;
963	} else if (flags.verbose) {
964		if (err == 0)
965			(void) printf("success\n");
966		else
967			(void) printf("failed (%u)\n", errno);
968	}
969
970	(void) changelist_postfix(clp);
971	changelist_free(clp);
972
973	return (err);
974}
975
976static int
977recv_destroy(libzfs_handle_t *hdl, const char *name, int baselen,
978    char *newname, recvflags_t flags)
979{
980	zfs_cmd_t zc = { 0 };
981	int err = 0;
982	prop_changelist_t *clp;
983	zfs_handle_t *zhp;
984	boolean_t defer = B_FALSE;
985	int spa_version;
986
987	zhp = zfs_open(hdl, name, ZFS_TYPE_DATASET);
988	if (zhp == NULL)
989		return (-1);
990	clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
991	    flags.force ? MS_FORCE : 0);
992	if (zfs_get_type(zhp) == ZFS_TYPE_SNAPSHOT &&
993	    zfs_spa_version(zhp, &spa_version) == 0 &&
994	    spa_version >= SPA_VERSION_USERREFS)
995		defer = B_TRUE;
996	zfs_close(zhp);
997	if (clp == NULL)
998		return (-1);
999	err = changelist_prefix(clp);
1000	if (err)
1001		return (err);
1002
1003	zc.zc_objset_type = DMU_OST_ZFS;
1004	zc.zc_defer_destroy = defer;
1005	(void) strlcpy(zc.zc_name, name, sizeof (zc.zc_name));
1006
1007	if (flags.verbose)
1008		(void) printf("attempting destroy %s\n", zc.zc_name);
1009	err = ioctl(hdl->libzfs_fd, ZFS_IOC_DESTROY, &zc);
1010	if (err == 0) {
1011		if (flags.verbose)
1012			(void) printf("success\n");
1013		changelist_remove(clp, zc.zc_name);
1014	}
1015
1016	(void) changelist_postfix(clp);
1017	changelist_free(clp);
1018
1019	/*
1020	 * Deferred destroy should always succeed. Since we can't tell
1021	 * if it destroyed the dataset or just marked it for deferred
1022	 * destroy, always do the rename just in case.
1023	 */
1024	if (err != 0 || defer)
1025		err = recv_rename(hdl, name, NULL, baselen, newname, flags);
1026
1027	return (err);
1028}
1029
1030typedef struct guid_to_name_data {
1031	uint64_t guid;
1032	char *name;
1033} guid_to_name_data_t;
1034
1035static int
1036guid_to_name_cb(zfs_handle_t *zhp, void *arg)
1037{
1038	guid_to_name_data_t *gtnd = arg;
1039	int err;
1040
1041	if (zhp->zfs_dmustats.dds_guid == gtnd->guid) {
1042		(void) strcpy(gtnd->name, zhp->zfs_name);
1043		return (EEXIST);
1044	}
1045	err = zfs_iter_children(zhp, guid_to_name_cb, gtnd);
1046	zfs_close(zhp);
1047	return (err);
1048}
1049
1050static int
1051guid_to_name(libzfs_handle_t *hdl, const char *parent, uint64_t guid,
1052    char *name)
1053{
1054	/* exhaustive search all local snapshots */
1055	guid_to_name_data_t gtnd;
1056	int err = 0;
1057	zfs_handle_t *zhp;
1058	char *cp;
1059
1060	gtnd.guid = guid;
1061	gtnd.name = name;
1062
1063	if (strchr(parent, '@') == NULL) {
1064		zhp = make_dataset_handle(hdl, parent);
1065		if (zhp != NULL) {
1066			err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1067			zfs_close(zhp);
1068			if (err == EEXIST)
1069				return (0);
1070		}
1071	}
1072
1073	cp = strchr(parent, '/');
1074	if (cp)
1075		*cp = '\0';
1076	zhp = make_dataset_handle(hdl, parent);
1077	if (cp)
1078		*cp = '/';
1079
1080	if (zhp) {
1081		err = zfs_iter_children(zhp, guid_to_name_cb, &gtnd);
1082		zfs_close(zhp);
1083	}
1084
1085	return (err == EEXIST ? 0 : ENOENT);
1086
1087}
1088
1089/*
1090 * Return true if dataset guid1 is created before guid2.
1091 */
1092static int
1093created_before(libzfs_handle_t *hdl, avl_tree_t *avl,
1094    uint64_t guid1, uint64_t guid2)
1095{
1096	nvlist_t *nvfs;
1097	char *fsname, *snapname;
1098	char buf[ZFS_MAXNAMELEN];
1099	int rv;
1100	zfs_node_t zn1, zn2;
1101
1102	if (guid2 == 0)
1103		return (0);
1104	if (guid1 == 0)
1105		return (1);
1106
1107	nvfs = fsavl_find(avl, guid1, &snapname);
1108	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1109	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1110	zn1.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1111	if (zn1.zn_handle == NULL)
1112		return (-1);
1113
1114	nvfs = fsavl_find(avl, guid2, &snapname);
1115	VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1116	(void) snprintf(buf, sizeof (buf), "%s@%s", fsname, snapname);
1117	zn2.zn_handle = zfs_open(hdl, buf, ZFS_TYPE_SNAPSHOT);
1118	if (zn2.zn_handle == NULL) {
1119		zfs_close(zn2.zn_handle);
1120		return (-1);
1121	}
1122
1123	rv = (zfs_snapshot_compare(&zn1, &zn2) == -1);
1124
1125	zfs_close(zn1.zn_handle);
1126	zfs_close(zn2.zn_handle);
1127
1128	return (rv);
1129}
1130
1131static int
1132recv_incremental_replication(libzfs_handle_t *hdl, const char *tofs,
1133    recvflags_t flags, nvlist_t *stream_nv, avl_tree_t *stream_avl)
1134{
1135	nvlist_t *local_nv;
1136	avl_tree_t *local_avl;
1137	nvpair_t *fselem, *nextfselem;
1138	char *tosnap, *fromsnap;
1139	char newname[ZFS_MAXNAMELEN];
1140	int error;
1141	boolean_t needagain, progress;
1142	char *s1, *s2;
1143
1144	VERIFY(0 == nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap));
1145	VERIFY(0 == nvlist_lookup_string(stream_nv, "tosnap", &tosnap));
1146
1147	if (flags.dryrun)
1148		return (0);
1149
1150again:
1151	needagain = progress = B_FALSE;
1152
1153	if ((error = gather_nvlist(hdl, tofs, fromsnap, NULL,
1154	    &local_nv, &local_avl)) != 0)
1155		return (error);
1156
1157	/*
1158	 * Process deletes and renames
1159	 */
1160	for (fselem = nvlist_next_nvpair(local_nv, NULL);
1161	    fselem; fselem = nextfselem) {
1162		nvlist_t *nvfs, *snaps;
1163		nvlist_t *stream_nvfs = NULL;
1164		nvpair_t *snapelem, *nextsnapelem;
1165		uint64_t fromguid = 0;
1166		uint64_t originguid = 0;
1167		uint64_t stream_originguid = 0;
1168		uint64_t parent_fromsnap_guid, stream_parent_fromsnap_guid;
1169		char *fsname, *stream_fsname;
1170
1171		nextfselem = nvlist_next_nvpair(local_nv, fselem);
1172
1173		VERIFY(0 == nvpair_value_nvlist(fselem, &nvfs));
1174		VERIFY(0 == nvlist_lookup_nvlist(nvfs, "snaps", &snaps));
1175		VERIFY(0 == nvlist_lookup_string(nvfs, "name", &fsname));
1176		VERIFY(0 == nvlist_lookup_uint64(nvfs, "parentfromsnap",
1177		    &parent_fromsnap_guid));
1178		(void) nvlist_lookup_uint64(nvfs, "origin", &originguid);
1179
1180		/*
1181		 * First find the stream's fs, so we can check for
1182		 * a different origin (due to "zfs promote")
1183		 */
1184		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1185		    snapelem; snapelem = nvlist_next_nvpair(snaps, snapelem)) {
1186			uint64_t thisguid;
1187
1188			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1189			stream_nvfs = fsavl_find(stream_avl, thisguid, NULL);
1190
1191			if (stream_nvfs != NULL)
1192				break;
1193		}
1194
1195		/* check for promote */
1196		(void) nvlist_lookup_uint64(stream_nvfs, "origin",
1197		    &stream_originguid);
1198		if (stream_nvfs && originguid != stream_originguid) {
1199			switch (created_before(hdl, local_avl,
1200			    stream_originguid, originguid)) {
1201			case 1: {
1202				/* promote it! */
1203				zfs_cmd_t zc = { 0 };
1204				nvlist_t *origin_nvfs;
1205				char *origin_fsname;
1206
1207				if (flags.verbose)
1208					(void) printf("promoting %s\n", fsname);
1209
1210				origin_nvfs = fsavl_find(local_avl, originguid,
1211				    NULL);
1212				VERIFY(0 == nvlist_lookup_string(origin_nvfs,
1213				    "name", &origin_fsname));
1214				(void) strlcpy(zc.zc_value, origin_fsname,
1215				    sizeof (zc.zc_value));
1216				(void) strlcpy(zc.zc_name, fsname,
1217				    sizeof (zc.zc_name));
1218				error = zfs_ioctl(hdl, ZFS_IOC_PROMOTE, &zc);
1219				if (error == 0)
1220					progress = B_TRUE;
1221				break;
1222			}
1223			default:
1224				break;
1225			case -1:
1226				fsavl_destroy(local_avl);
1227				nvlist_free(local_nv);
1228				return (-1);
1229			}
1230			/*
1231			 * We had/have the wrong origin, therefore our
1232			 * list of snapshots is wrong.  Need to handle
1233			 * them on the next pass.
1234			 */
1235			needagain = B_TRUE;
1236			continue;
1237		}
1238
1239		for (snapelem = nvlist_next_nvpair(snaps, NULL);
1240		    snapelem; snapelem = nextsnapelem) {
1241			uint64_t thisguid;
1242			char *stream_snapname;
1243			nvlist_t *found, *props;
1244
1245			nextsnapelem = nvlist_next_nvpair(snaps, snapelem);
1246
1247			VERIFY(0 == nvpair_value_uint64(snapelem, &thisguid));
1248			found = fsavl_find(stream_avl, thisguid,
1249			    &stream_snapname);
1250
1251			/* check for delete */
1252			if (found == NULL) {
1253				char name[ZFS_MAXNAMELEN];
1254
1255				if (!flags.force)
1256					continue;
1257
1258				(void) snprintf(name, sizeof (name), "%s@%s",
1259				    fsname, nvpair_name(snapelem));
1260
1261				error = recv_destroy(hdl, name,
1262				    strlen(fsname)+1, newname, flags);
1263				if (error)
1264					needagain = B_TRUE;
1265				else
1266					progress = B_TRUE;
1267				continue;
1268			}
1269
1270			stream_nvfs = found;
1271
1272			if (0 == nvlist_lookup_nvlist(stream_nvfs, "snapprops",
1273			    &props) && 0 == nvlist_lookup_nvlist(props,
1274			    stream_snapname, &props)) {
1275				zfs_cmd_t zc = { 0 };
1276
1277				zc.zc_cookie = B_TRUE; /* clear current props */
1278				(void) snprintf(zc.zc_name, sizeof (zc.zc_name),
1279				    "%s@%s", fsname, nvpair_name(snapelem));
1280				if (zcmd_write_src_nvlist(hdl, &zc,
1281				    props) == 0) {
1282					(void) zfs_ioctl(hdl,
1283					    ZFS_IOC_SET_PROP, &zc);
1284					zcmd_free_nvlists(&zc);
1285				}
1286			}
1287
1288			/* check for different snapname */
1289			if (strcmp(nvpair_name(snapelem),
1290			    stream_snapname) != 0) {
1291				char name[ZFS_MAXNAMELEN];
1292				char tryname[ZFS_MAXNAMELEN];
1293
1294				(void) snprintf(name, sizeof (name), "%s@%s",
1295				    fsname, nvpair_name(snapelem));
1296				(void) snprintf(tryname, sizeof (name), "%s@%s",
1297				    fsname, stream_snapname);
1298
1299				error = recv_rename(hdl, name, tryname,
1300				    strlen(fsname)+1, newname, flags);
1301				if (error)
1302					needagain = B_TRUE;
1303				else
1304					progress = B_TRUE;
1305			}
1306
1307			if (strcmp(stream_snapname, fromsnap) == 0)
1308				fromguid = thisguid;
1309		}
1310
1311		/* check for delete */
1312		if (stream_nvfs == NULL) {
1313			if (!flags.force)
1314				continue;
1315
1316			error = recv_destroy(hdl, fsname, strlen(tofs)+1,
1317			    newname, flags);
1318			if (error)
1319				needagain = B_TRUE;
1320			else
1321				progress = B_TRUE;
1322			continue;
1323		}
1324
1325		if (fromguid == 0 && flags.verbose) {
1326			(void) printf("local fs %s does not have fromsnap "
1327			    "(%s in stream); must have been deleted locally; "
1328			    "ignoring\n", fsname, fromsnap);
1329			continue;
1330		}
1331
1332		VERIFY(0 == nvlist_lookup_string(stream_nvfs,
1333		    "name", &stream_fsname));
1334		VERIFY(0 == nvlist_lookup_uint64(stream_nvfs,
1335		    "parentfromsnap", &stream_parent_fromsnap_guid));
1336
1337		/* check for rename */
1338		if ((stream_parent_fromsnap_guid != 0 &&
1339		    stream_parent_fromsnap_guid != parent_fromsnap_guid) ||
1340		    ((s1 = strrchr(fsname, '/')) &&
1341		    (s2 = strrchr(stream_fsname, '/')) &&
1342		    strcmp(s1, s2) != 0)) {
1343			nvlist_t *parent;
1344			char tryname[ZFS_MAXNAMELEN];
1345
1346			parent = fsavl_find(local_avl,
1347			    stream_parent_fromsnap_guid, NULL);
1348			/*
1349			 * NB: parent might not be found if we used the
1350			 * tosnap for stream_parent_fromsnap_guid,
1351			 * because the parent is a newly-created fs;
1352			 * we'll be able to rename it after we recv the
1353			 * new fs.
1354			 */
1355			if (parent != NULL) {
1356				char *pname;
1357
1358				VERIFY(0 == nvlist_lookup_string(parent, "name",
1359				    &pname));
1360				(void) snprintf(tryname, sizeof (tryname),
1361				    "%s%s", pname, strrchr(stream_fsname, '/'));
1362			} else {
1363				tryname[0] = '\0';
1364				if (flags.verbose) {
1365					(void) printf("local fs %s new parent "
1366					    "not found\n", fsname);
1367				}
1368			}
1369
1370			error = recv_rename(hdl, fsname, tryname,
1371			    strlen(tofs)+1, newname, flags);
1372			if (error)
1373				needagain = B_TRUE;
1374			else
1375				progress = B_TRUE;
1376		}
1377	}
1378
1379	fsavl_destroy(local_avl);
1380	nvlist_free(local_nv);
1381
1382	if (needagain && progress) {
1383		/* do another pass to fix up temporary names */
1384		if (flags.verbose)
1385			(void) printf("another pass:\n");
1386		goto again;
1387	}
1388
1389	return (needagain);
1390}
1391
1392static int
1393zfs_receive_package(libzfs_handle_t *hdl, int fd, const char *destname,
1394    recvflags_t flags, dmu_replay_record_t *drr, zio_cksum_t *zc,
1395    char **top_zfs)
1396{
1397	nvlist_t *stream_nv = NULL;
1398	avl_tree_t *stream_avl = NULL;
1399	char *fromsnap = NULL;
1400	char tofs[ZFS_MAXNAMELEN];
1401	char errbuf[1024];
1402	dmu_replay_record_t drre;
1403	int error;
1404	boolean_t anyerr = B_FALSE;
1405	boolean_t softerr = B_FALSE;
1406
1407	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1408	    "cannot receive"));
1409
1410	if (strchr(destname, '@')) {
1411		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1412		    "can not specify snapshot name for multi-snapshot stream"));
1413		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
1414	}
1415
1416	assert(drr->drr_type == DRR_BEGIN);
1417	assert(drr->drr_u.drr_begin.drr_magic == DMU_BACKUP_MAGIC);
1418	assert(drr->drr_u.drr_begin.drr_version == DMU_BACKUP_HEADER_VERSION);
1419
1420	/*
1421	 * Read in the nvlist from the stream.
1422	 */
1423	if (drr->drr_payloadlen != 0) {
1424		if (!flags.isprefix) {
1425			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1426			    "must use -d to receive replication "
1427			    "(send -R) stream"));
1428			return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
1429		}
1430
1431		error = recv_read_nvlist(hdl, fd, drr->drr_payloadlen,
1432		    &stream_nv, flags.byteswap, zc);
1433		if (error) {
1434			error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1435			goto out;
1436		}
1437	}
1438
1439	/*
1440	 * Read in the end record and verify checksum.
1441	 */
1442	if (0 != (error = recv_read(hdl, fd, &drre, sizeof (drre),
1443	    flags.byteswap, NULL)))
1444		goto out;
1445	if (flags.byteswap) {
1446		drre.drr_type = BSWAP_32(drre.drr_type);
1447		drre.drr_u.drr_end.drr_checksum.zc_word[0] =
1448		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[0]);
1449		drre.drr_u.drr_end.drr_checksum.zc_word[1] =
1450		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[1]);
1451		drre.drr_u.drr_end.drr_checksum.zc_word[2] =
1452		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[2]);
1453		drre.drr_u.drr_end.drr_checksum.zc_word[3] =
1454		    BSWAP_64(drre.drr_u.drr_end.drr_checksum.zc_word[3]);
1455	}
1456	if (drre.drr_type != DRR_END) {
1457		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1458		goto out;
1459	}
1460	if (!ZIO_CHECKSUM_EQUAL(drre.drr_u.drr_end.drr_checksum, *zc)) {
1461		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1462		    "incorrect header checksum"));
1463		error = zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1464		goto out;
1465	}
1466
1467	(void) nvlist_lookup_string(stream_nv, "fromsnap", &fromsnap);
1468
1469	if (drr->drr_payloadlen != 0) {
1470		nvlist_t *stream_fss;
1471
1472		VERIFY(0 == nvlist_lookup_nvlist(stream_nv, "fss",
1473		    &stream_fss));
1474		if ((stream_avl = fsavl_create(stream_fss)) == NULL) {
1475			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1476			    "couldn't allocate avl tree"));
1477			error = zfs_error(hdl, EZFS_NOMEM, errbuf);
1478			goto out;
1479		}
1480
1481		if (fromsnap != NULL) {
1482			(void) strlcpy(tofs, destname, ZFS_MAXNAMELEN);
1483			if (flags.isprefix) {
1484				int i = strcspn(drr->drr_u.drr_begin.drr_toname,
1485				    "/@");
1486				/* zfs_receive_one() will create_parents() */
1487				(void) strlcat(tofs,
1488				    &drr->drr_u.drr_begin.drr_toname[i],
1489				    ZFS_MAXNAMELEN);
1490				*strchr(tofs, '@') = '\0';
1491			}
1492			softerr = recv_incremental_replication(hdl, tofs,
1493			    flags, stream_nv, stream_avl);
1494		}
1495	}
1496
1497
1498	/* Finally, receive each contained stream */
1499	do {
1500		/*
1501		 * we should figure out if it has a recoverable
1502		 * error, in which case do a recv_skip() and drive on.
1503		 * Note, if we fail due to already having this guid,
1504		 * zfs_receive_one() will take care of it (ie,
1505		 * recv_skip() and return 0).
1506		 */
1507		error = zfs_receive_impl(hdl, destname, flags, fd,
1508		    stream_avl, top_zfs);
1509		if (error == ENODATA) {
1510			error = 0;
1511			break;
1512		}
1513		anyerr |= error;
1514	} while (error == 0);
1515
1516	if (drr->drr_payloadlen != 0 && fromsnap != NULL) {
1517		/*
1518		 * Now that we have the fs's they sent us, try the
1519		 * renames again.
1520		 */
1521		softerr = recv_incremental_replication(hdl, tofs, flags,
1522		    stream_nv, stream_avl);
1523	}
1524
1525out:
1526	fsavl_destroy(stream_avl);
1527	if (stream_nv)
1528		nvlist_free(stream_nv);
1529	if (softerr)
1530		error = -2;
1531	if (anyerr)
1532		error = -1;
1533	return (error);
1534}
1535
1536static int
1537recv_skip(libzfs_handle_t *hdl, int fd, boolean_t byteswap)
1538{
1539	dmu_replay_record_t *drr;
1540	void *buf = malloc(1<<20);
1541
1542	/* XXX would be great to use lseek if possible... */
1543	drr = buf;
1544
1545	while (recv_read(hdl, fd, drr, sizeof (dmu_replay_record_t),
1546	    byteswap, NULL) == 0) {
1547		if (byteswap)
1548			drr->drr_type = BSWAP_32(drr->drr_type);
1549
1550		switch (drr->drr_type) {
1551		case DRR_BEGIN:
1552			/* NB: not to be used on v2 stream packages */
1553			assert(drr->drr_payloadlen == 0);
1554			break;
1555
1556		case DRR_END:
1557			free(buf);
1558			return (0);
1559
1560		case DRR_OBJECT:
1561			if (byteswap) {
1562				drr->drr_u.drr_object.drr_bonuslen =
1563				    BSWAP_32(drr->drr_u.drr_object.
1564				    drr_bonuslen);
1565			}
1566			(void) recv_read(hdl, fd, buf,
1567			    P2ROUNDUP(drr->drr_u.drr_object.drr_bonuslen, 8),
1568			    B_FALSE, NULL);
1569			break;
1570
1571		case DRR_WRITE:
1572			if (byteswap) {
1573				drr->drr_u.drr_write.drr_length =
1574				    BSWAP_64(drr->drr_u.drr_write.drr_length);
1575			}
1576			(void) recv_read(hdl, fd, buf,
1577			    drr->drr_u.drr_write.drr_length, B_FALSE, NULL);
1578			break;
1579
1580		case DRR_FREEOBJECTS:
1581		case DRR_FREE:
1582			break;
1583
1584		default:
1585			assert(!"invalid record type");
1586		}
1587	}
1588
1589	free(buf);
1590	return (-1);
1591}
1592
1593/*
1594 * Restores a backup of tosnap from the file descriptor specified by infd.
1595 */
1596static int
1597zfs_receive_one(libzfs_handle_t *hdl, int infd, const char *tosnap,
1598    recvflags_t flags, dmu_replay_record_t *drr,
1599    dmu_replay_record_t *drr_noswap, avl_tree_t *stream_avl,
1600    char **top_zfs)
1601{
1602	zfs_cmd_t zc = { 0 };
1603	time_t begin_time;
1604	int ioctl_err, ioctl_errno, err, choplen;
1605	char *cp;
1606	struct drr_begin *drrb = &drr->drr_u.drr_begin;
1607	char errbuf[1024];
1608	char chopprefix[ZFS_MAXNAMELEN];
1609	boolean_t newfs = B_FALSE;
1610	boolean_t stream_wantsnewfs;
1611	uint64_t parent_snapguid = 0;
1612	prop_changelist_t *clp = NULL;
1613	nvlist_t *snapprops_nvlist = NULL;
1614
1615	begin_time = time(NULL);
1616
1617	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1618	    "cannot receive"));
1619
1620	if (stream_avl != NULL) {
1621		char *snapname;
1622		nvlist_t *fs = fsavl_find(stream_avl, drrb->drr_toguid,
1623		    &snapname);
1624		nvlist_t *props;
1625		int ret;
1626
1627		(void) nvlist_lookup_uint64(fs, "parentfromsnap",
1628		    &parent_snapguid);
1629		err = nvlist_lookup_nvlist(fs, "props", &props);
1630		if (err)
1631			VERIFY(0 == nvlist_alloc(&props, NV_UNIQUE_NAME, 0));
1632
1633		if (flags.canmountoff) {
1634			VERIFY(0 == nvlist_add_uint64(props,
1635			    zfs_prop_to_name(ZFS_PROP_CANMOUNT), 0));
1636		}
1637		ret = zcmd_write_src_nvlist(hdl, &zc, props);
1638		if (err)
1639			nvlist_free(props);
1640
1641		if (0 == nvlist_lookup_nvlist(fs, "snapprops", &props)) {
1642			VERIFY(0 == nvlist_lookup_nvlist(props,
1643			    snapname, &snapprops_nvlist));
1644		}
1645
1646		if (ret != 0)
1647			return (-1);
1648	}
1649
1650	/*
1651	 * Determine how much of the snapshot name stored in the stream
1652	 * we are going to tack on to the name they specified on the
1653	 * command line, and how much we are going to chop off.
1654	 *
1655	 * If they specified a snapshot, chop the entire name stored in
1656	 * the stream.
1657	 */
1658	(void) strcpy(chopprefix, drrb->drr_toname);
1659	if (flags.isprefix) {
1660		/*
1661		 * They specified a fs with -d, we want to tack on
1662		 * everything but the pool name stored in the stream
1663		 */
1664		if (strchr(tosnap, '@')) {
1665			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
1666			    "argument - snapshot not allowed with -d"));
1667			return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
1668		}
1669		cp = strchr(chopprefix, '/');
1670		if (cp == NULL)
1671			cp = strchr(chopprefix, '@');
1672		*cp = '\0';
1673	} else if (strchr(tosnap, '@') == NULL) {
1674		/*
1675		 * If they specified a filesystem without -d, we want to
1676		 * tack on everything after the fs specified in the
1677		 * first name from the stream.
1678		 */
1679		cp = strchr(chopprefix, '@');
1680		*cp = '\0';
1681	}
1682	choplen = strlen(chopprefix);
1683
1684	/*
1685	 * Determine name of destination snapshot, store in zc_value.
1686	 */
1687	(void) strcpy(zc.zc_value, tosnap);
1688	(void) strncat(zc.zc_value, drrb->drr_toname+choplen,
1689	    sizeof (zc.zc_value));
1690	if (!zfs_name_valid(zc.zc_value, ZFS_TYPE_SNAPSHOT)) {
1691		zcmd_free_nvlists(&zc);
1692		return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
1693	}
1694
1695	/*
1696	 * Determine the name of the origin snapshot, store in zc_string.
1697	 */
1698	if (drrb->drr_flags & DRR_FLAG_CLONE) {
1699		if (guid_to_name(hdl, tosnap,
1700		    drrb->drr_fromguid, zc.zc_string) != 0) {
1701			zcmd_free_nvlists(&zc);
1702			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1703			    "local origin for clone %s does not exist"),
1704			    zc.zc_value);
1705			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1706		}
1707		if (flags.verbose)
1708			(void) printf("found clone origin %s\n", zc.zc_string);
1709	}
1710
1711	stream_wantsnewfs = (drrb->drr_fromguid == NULL ||
1712	    (drrb->drr_flags & DRR_FLAG_CLONE));
1713
1714	if (stream_wantsnewfs) {
1715		/*
1716		 * if the parent fs does not exist, look for it based on
1717		 * the parent snap GUID
1718		 */
1719		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1720		    "cannot receive new filesystem stream"));
1721
1722		(void) strcpy(zc.zc_name, zc.zc_value);
1723		cp = strrchr(zc.zc_name, '/');
1724		if (cp)
1725			*cp = '\0';
1726		if (cp &&
1727		    !zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
1728			char suffix[ZFS_MAXNAMELEN];
1729			(void) strcpy(suffix, strrchr(zc.zc_value, '/'));
1730			if (guid_to_name(hdl, tosnap, parent_snapguid,
1731			    zc.zc_value) == 0) {
1732				*strchr(zc.zc_value, '@') = '\0';
1733				(void) strcat(zc.zc_value, suffix);
1734			}
1735		}
1736	} else {
1737		/*
1738		 * if the fs does not exist, look for it based on the
1739		 * fromsnap GUID
1740		 */
1741		(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
1742		    "cannot receive incremental stream"));
1743
1744		(void) strcpy(zc.zc_name, zc.zc_value);
1745		*strchr(zc.zc_name, '@') = '\0';
1746
1747		if (!zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
1748			char snap[ZFS_MAXNAMELEN];
1749			(void) strcpy(snap, strchr(zc.zc_value, '@'));
1750			if (guid_to_name(hdl, tosnap, drrb->drr_fromguid,
1751			    zc.zc_value) == 0) {
1752				*strchr(zc.zc_value, '@') = '\0';
1753				(void) strcat(zc.zc_value, snap);
1754			}
1755		}
1756	}
1757
1758	(void) strcpy(zc.zc_name, zc.zc_value);
1759	*strchr(zc.zc_name, '@') = '\0';
1760
1761	if (zfs_dataset_exists(hdl, zc.zc_name, ZFS_TYPE_DATASET)) {
1762		zfs_handle_t *zhp;
1763		/*
1764		 * Destination fs exists.  Therefore this should either
1765		 * be an incremental, or the stream specifies a new fs
1766		 * (full stream or clone) and they want us to blow it
1767		 * away (and have therefore specified -F and removed any
1768		 * snapshots).
1769		 */
1770
1771		if (stream_wantsnewfs) {
1772			if (!flags.force) {
1773				zcmd_free_nvlists(&zc);
1774				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1775				    "destination '%s' exists\n"
1776				    "must specify -F to overwrite it"),
1777				    zc.zc_name);
1778				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
1779			}
1780			if (ioctl(hdl->libzfs_fd, ZFS_IOC_SNAPSHOT_LIST_NEXT,
1781			    &zc) == 0) {
1782				zcmd_free_nvlists(&zc);
1783				zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1784				    "destination has snapshots (eg. %s)\n"
1785				    "must destroy them to overwrite it"),
1786				    zc.zc_name);
1787				return (zfs_error(hdl, EZFS_EXISTS, errbuf));
1788			}
1789		}
1790
1791		if ((zhp = zfs_open(hdl, zc.zc_name,
1792		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME)) == NULL) {
1793			zcmd_free_nvlists(&zc);
1794			return (-1);
1795		}
1796
1797		if (stream_wantsnewfs &&
1798		    zhp->zfs_dmustats.dds_origin[0]) {
1799			zcmd_free_nvlists(&zc);
1800			zfs_close(zhp);
1801			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1802			    "destination '%s' is a clone\n"
1803			    "must destroy it to overwrite it"),
1804			    zc.zc_name);
1805			return (zfs_error(hdl, EZFS_EXISTS, errbuf));
1806		}
1807
1808		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_FILESYSTEM &&
1809		    stream_wantsnewfs) {
1810			/* We can't do online recv in this case */
1811			clp = changelist_gather(zhp, ZFS_PROP_NAME, 0, 0);
1812			if (clp == NULL) {
1813				zfs_close(zhp);
1814				zcmd_free_nvlists(&zc);
1815				return (-1);
1816			}
1817			if (changelist_prefix(clp) != 0) {
1818				changelist_free(clp);
1819				zfs_close(zhp);
1820				zcmd_free_nvlists(&zc);
1821				return (-1);
1822			}
1823		}
1824		if (!flags.dryrun && zhp->zfs_type == ZFS_TYPE_VOLUME &&
1825		    zvol_remove_link(hdl, zhp->zfs_name) != 0) {
1826			zfs_close(zhp);
1827			zcmd_free_nvlists(&zc);
1828			return (-1);
1829		}
1830		zfs_close(zhp);
1831	} else {
1832		/*
1833		 * Destination filesystem does not exist.  Therefore we better
1834		 * be creating a new filesystem (either from a full backup, or
1835		 * a clone).  It would therefore be invalid if the user
1836		 * specified only the pool name (i.e. if the destination name
1837		 * contained no slash character).
1838		 */
1839		if (!stream_wantsnewfs ||
1840		    (cp = strrchr(zc.zc_name, '/')) == NULL) {
1841			zcmd_free_nvlists(&zc);
1842			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1843			    "destination '%s' does not exist"), zc.zc_name);
1844			return (zfs_error(hdl, EZFS_NOENT, errbuf));
1845		}
1846
1847		/*
1848		 * Trim off the final dataset component so we perform the
1849		 * recvbackup ioctl to the filesystems's parent.
1850		 */
1851		*cp = '\0';
1852
1853		if (flags.isprefix && !flags.dryrun &&
1854		    create_parents(hdl, zc.zc_value, strlen(tosnap)) != 0) {
1855			zcmd_free_nvlists(&zc);
1856			return (zfs_error(hdl, EZFS_BADRESTORE, errbuf));
1857		}
1858
1859		newfs = B_TRUE;
1860	}
1861
1862	zc.zc_begin_record = drr_noswap->drr_u.drr_begin;
1863	zc.zc_cookie = infd;
1864	zc.zc_guid = flags.force;
1865	if (flags.verbose) {
1866		(void) printf("%s %s stream of %s into %s\n",
1867		    flags.dryrun ? "would receive" : "receiving",
1868		    drrb->drr_fromguid ? "incremental" : "full",
1869		    drrb->drr_toname, zc.zc_value);
1870		(void) fflush(stdout);
1871	}
1872
1873	if (flags.dryrun) {
1874		zcmd_free_nvlists(&zc);
1875		return (recv_skip(hdl, infd, flags.byteswap));
1876	}
1877
1878	err = ioctl_err = zfs_ioctl(hdl, ZFS_IOC_RECV, &zc);
1879	ioctl_errno = errno;
1880	zcmd_free_nvlists(&zc);
1881
1882	if (err == 0 && snapprops_nvlist) {
1883		zfs_cmd_t zc2 = { 0 };
1884
1885		(void) strcpy(zc2.zc_name, zc.zc_value);
1886		if (zcmd_write_src_nvlist(hdl, &zc2, snapprops_nvlist) == 0) {
1887			(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc2);
1888			zcmd_free_nvlists(&zc2);
1889		}
1890	}
1891
1892	if (err && (ioctl_errno == ENOENT || ioctl_errno == ENODEV)) {
1893		/*
1894		 * It may be that this snapshot already exists,
1895		 * in which case we want to consume & ignore it
1896		 * rather than failing.
1897		 */
1898		avl_tree_t *local_avl;
1899		nvlist_t *local_nv, *fs;
1900		char *cp = strchr(zc.zc_value, '@');
1901
1902		/*
1903		 * XXX Do this faster by just iterating over snaps in
1904		 * this fs.  Also if zc_value does not exist, we will
1905		 * get a strange "does not exist" error message.
1906		 */
1907		*cp = '\0';
1908		if (gather_nvlist(hdl, zc.zc_value, NULL, NULL,
1909		    &local_nv, &local_avl) == 0) {
1910			*cp = '@';
1911			fs = fsavl_find(local_avl, drrb->drr_toguid, NULL);
1912			fsavl_destroy(local_avl);
1913			nvlist_free(local_nv);
1914
1915			if (fs != NULL) {
1916				if (flags.verbose) {
1917					(void) printf("snap %s already exists; "
1918					    "ignoring\n", zc.zc_value);
1919				}
1920				ioctl_err = recv_skip(hdl, infd,
1921				    flags.byteswap);
1922			}
1923		}
1924		*cp = '@';
1925	}
1926
1927
1928	if (ioctl_err != 0) {
1929		switch (ioctl_errno) {
1930		case ENODEV:
1931			cp = strchr(zc.zc_value, '@');
1932			*cp = '\0';
1933			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1934			    "most recent snapshot of %s does not\n"
1935			    "match incremental source"), zc.zc_value);
1936			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
1937			*cp = '@';
1938			break;
1939		case ETXTBSY:
1940			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1941			    "destination %s has been modified\n"
1942			    "since most recent snapshot"), zc.zc_name);
1943			(void) zfs_error(hdl, EZFS_BADRESTORE, errbuf);
1944			break;
1945		case EEXIST:
1946			cp = strchr(zc.zc_value, '@');
1947			if (newfs) {
1948				/* it's the containing fs that exists */
1949				*cp = '\0';
1950			}
1951			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1952			    "destination already exists"));
1953			(void) zfs_error_fmt(hdl, EZFS_EXISTS,
1954			    dgettext(TEXT_DOMAIN, "cannot restore to %s"),
1955			    zc.zc_value);
1956			*cp = '@';
1957			break;
1958		case EINVAL:
1959			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1960			break;
1961		case ECKSUM:
1962			zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
1963			    "invalid stream (checksum mismatch)"));
1964			(void) zfs_error(hdl, EZFS_BADSTREAM, errbuf);
1965			break;
1966		default:
1967			(void) zfs_standard_error(hdl, ioctl_errno, errbuf);
1968		}
1969	}
1970
1971	/*
1972	 * Mount or recreate the /dev links for the target filesystem
1973	 * (if created, or if we tore them down to do an incremental
1974	 * restore), and the /dev links for the new snapshot (if
1975	 * created). Also mount any children of the target filesystem
1976	 * if we did a replication receive (indicated by stream_avl
1977	 * being non-NULL).
1978	 */
1979	cp = strchr(zc.zc_value, '@');
1980	if (cp && (ioctl_err == 0 || !newfs)) {
1981		zfs_handle_t *h;
1982
1983		*cp = '\0';
1984		h = zfs_open(hdl, zc.zc_value,
1985		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
1986		if (h != NULL) {
1987			if (h->zfs_type == ZFS_TYPE_VOLUME) {
1988				*cp = '@';
1989				err = zvol_create_link(hdl, h->zfs_name);
1990				if (err == 0 && ioctl_err == 0)
1991					err = zvol_create_link(hdl,
1992					    zc.zc_value);
1993			} else if (newfs || stream_avl) {
1994				/*
1995				 * Track the first/top of hierarchy fs,
1996				 * for mounting and sharing later.
1997				 */
1998				if (top_zfs && *top_zfs == NULL)
1999					*top_zfs = zfs_strdup(hdl, zc.zc_value);
2000			}
2001			zfs_close(h);
2002		}
2003		*cp = '@';
2004	}
2005
2006	if (clp) {
2007		err |= changelist_postfix(clp);
2008		changelist_free(clp);
2009	}
2010
2011	if (err || ioctl_err)
2012		return (-1);
2013
2014	if (flags.verbose) {
2015		char buf1[64];
2016		char buf2[64];
2017		uint64_t bytes = zc.zc_cookie;
2018		time_t delta = time(NULL) - begin_time;
2019		if (delta == 0)
2020			delta = 1;
2021		zfs_nicenum(bytes, buf1, sizeof (buf1));
2022		zfs_nicenum(bytes/delta, buf2, sizeof (buf1));
2023
2024		(void) printf("received %sB stream in %lu seconds (%sB/sec)\n",
2025		    buf1, delta, buf2);
2026	}
2027
2028	return (0);
2029}
2030
2031static int
2032zfs_receive_impl(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
2033    int infd, avl_tree_t *stream_avl, char **top_zfs)
2034{
2035	int err;
2036	dmu_replay_record_t drr, drr_noswap;
2037	struct drr_begin *drrb = &drr.drr_u.drr_begin;
2038	char errbuf[1024];
2039	zio_cksum_t zcksum = { 0 };
2040
2041	(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
2042	    "cannot receive"));
2043
2044	if (flags.isprefix &&
2045	    !zfs_dataset_exists(hdl, tosnap, ZFS_TYPE_DATASET)) {
2046		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "specified fs "
2047		    "(%s) does not exist"), tosnap);
2048		return (zfs_error(hdl, EZFS_NOENT, errbuf));
2049	}
2050
2051	/* read in the BEGIN record */
2052	if (0 != (err = recv_read(hdl, infd, &drr, sizeof (drr), B_FALSE,
2053	    &zcksum)))
2054		return (err);
2055
2056	if (drr.drr_type == DRR_END || drr.drr_type == BSWAP_32(DRR_END)) {
2057		/* It's the double end record at the end of a package */
2058		return (ENODATA);
2059	}
2060
2061	/* the kernel needs the non-byteswapped begin record */
2062	drr_noswap = drr;
2063
2064	flags.byteswap = B_FALSE;
2065	if (drrb->drr_magic == BSWAP_64(DMU_BACKUP_MAGIC)) {
2066		/*
2067		 * We computed the checksum in the wrong byteorder in
2068		 * recv_read() above; do it again correctly.
2069		 */
2070		bzero(&zcksum, sizeof (zio_cksum_t));
2071		fletcher_4_incremental_byteswap(&drr, sizeof (drr), &zcksum);
2072		flags.byteswap = B_TRUE;
2073
2074		drr.drr_type = BSWAP_32(drr.drr_type);
2075		drr.drr_payloadlen = BSWAP_32(drr.drr_payloadlen);
2076		drrb->drr_magic = BSWAP_64(drrb->drr_magic);
2077		drrb->drr_version = BSWAP_64(drrb->drr_version);
2078		drrb->drr_creation_time = BSWAP_64(drrb->drr_creation_time);
2079		drrb->drr_type = BSWAP_32(drrb->drr_type);
2080		drrb->drr_flags = BSWAP_32(drrb->drr_flags);
2081		drrb->drr_toguid = BSWAP_64(drrb->drr_toguid);
2082		drrb->drr_fromguid = BSWAP_64(drrb->drr_fromguid);
2083	}
2084
2085	if (drrb->drr_magic != DMU_BACKUP_MAGIC || drr.drr_type != DRR_BEGIN) {
2086		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2087		    "stream (bad magic number)"));
2088		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2089	}
2090
2091	if (strchr(drrb->drr_toname, '@') == NULL) {
2092		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN, "invalid "
2093		    "stream (bad snapshot name)"));
2094		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2095	}
2096
2097	if (drrb->drr_version == DMU_BACKUP_STREAM_VERSION) {
2098		return (zfs_receive_one(hdl, infd, tosnap, flags,
2099		    &drr, &drr_noswap, stream_avl, top_zfs));
2100	} else if (drrb->drr_version == DMU_BACKUP_HEADER_VERSION) {
2101		return (zfs_receive_package(hdl, infd, tosnap, flags,
2102		    &drr, &zcksum, top_zfs));
2103	} else {
2104		zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
2105		    "stream is unsupported version %llu"),
2106		    drrb->drr_version);
2107		return (zfs_error(hdl, EZFS_BADSTREAM, errbuf));
2108	}
2109}
2110
2111/*
2112 * Restores a backup of tosnap from the file descriptor specified by infd.
2113 * Return 0 on total success, -2 if some things couldn't be
2114 * destroyed/renamed/promoted, -1 if some things couldn't be received.
2115 * (-1 will override -2).
2116 */
2117int
2118zfs_receive(libzfs_handle_t *hdl, const char *tosnap, recvflags_t flags,
2119    int infd, avl_tree_t *stream_avl)
2120{
2121	char *top_zfs = NULL;
2122	int err;
2123
2124	err = zfs_receive_impl(hdl, tosnap, flags, infd, stream_avl, &top_zfs);
2125
2126	if (err == 0 && !flags.nomount && top_zfs) {
2127		zfs_handle_t *zhp;
2128		prop_changelist_t *clp;
2129
2130		zhp = zfs_open(hdl, top_zfs, ZFS_TYPE_FILESYSTEM);
2131		if (zhp != NULL) {
2132			clp = changelist_gather(zhp, ZFS_PROP_MOUNTPOINT,
2133			    CL_GATHER_MOUNT_ALWAYS, 0);
2134			zfs_close(zhp);
2135			if (clp != NULL) {
2136				/* mount and share received datasets */
2137				err = changelist_postfix(clp);
2138				changelist_free(clp);
2139			}
2140		}
2141		if (zhp == NULL || clp == NULL || err)
2142			err = -1;
2143	}
2144	if (top_zfs)
2145		free(top_zfs);
2146
2147	return (err);
2148}
2149