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