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