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