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