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