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