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