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