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