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