Debian Codegraph @

receiver.c

raw symbols SCIP
1 /*
2 * Routines only used by the receiving process.
3 *
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2023 Wayne Davison
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
20 */
21
22 #include "rsync.h"
23 #include "inums.h"
24
25 extern int dry_run;
26 extern int do_xfers;
27 extern int am_root;
28 extern int am_daemon;
29 extern int am_server;
30 extern int inc_recurse;
31 extern int log_before_transfer;
32 extern int stdout_format_has_i;
33 extern int logfile_format_has_i;
34 extern int want_xattr_optim;
35 extern int csum_length;
36 extern int read_batch;
37 extern int write_batch;
38 extern int batch_gen_fd;
39 extern int protocol_version;
40 extern int relative_paths;
41 extern int preserve_hard_links;
42 extern int preserve_perms;
43 extern int write_devices;
44 extern int preserve_xattrs;
45 extern int do_fsync;
46 extern int basis_dir_cnt;
47 extern int make_backups;
48 extern int cleanup_got_literal;
49 extern int remove_source_files;
50 extern int append_mode;
51 extern int sparse_files;
52 extern int preallocate_files;
53 extern int keep_partial;
54 extern int checksum_seed;
55 extern int whole_file;
56 extern int inplace;
57 extern int inplace_partial;
58 extern int allowed_lull;
59 extern int delay_updates;
60 extern BOOL want_progress_now;
61 extern mode_t orig_umask;
62 extern struct stats stats;
63 extern char *tmpdir;
64 extern char *partial_dir;
65 extern char *basis_dir[MAX_BASIS_DIRS+1];
66 extern char sender_file_sum[MAX_DIGEST_LEN];
67 extern struct file_list *cur_flist, *first_flist, *dir_flist;
68 extern filter_rule_list daemon_filter_list;
69 extern OFF_T preallocated_len;
70 extern int fuzzy_basis;
71
72 extern struct name_num_item *xfer_sum_nni;
73 extern int xfer_sum_len;
74 extern int use_secure_symlinks;
75 extern int operator_path_resolve;
76
77 static struct bitbag *delayed_bits = NULL;
78 static int phase = 0, redoing = 0;
79 static flist_ndx_list batch_redo_list;
80 /* This is non-0 when we are updating the basis file or an identical copy: */
81 static int updating_basis_or_equiv;
82
83 #define TMPNAME_SUFFIX ".XXXXXX"
84 #define TMPNAME_SUFFIX_LEN ((int)sizeof TMPNAME_SUFFIX - 1)
85 #define MAX_UNIQUE_NUMBER 999999
86 #define MAX_UNIQUE_LOOP 100
87
88 /* Open a basis/output path that may legitimately be an operator-trusted
89 * ABSOLUTE path -- e.g. an absolute --partial-dir ("a directory reserved for
90 * partial-dir work") or --backup-dir. secure_relative_open() deliberately
91 * rejects an absolute relpath, so feeding it the whole absolute partialptr
92 * (with a NULL basedir) returns EINVAL: the basis fd is then -1, no basis is
93 * mapped, and receive_data() omits every matched block from the whole-file
94 * verification checksum -> a spurious "failed verification" that strands the
95 * (correct) data in the partial-dir forever.
96 *
97 * The operator's directory is trusted; only the leaf basename is peer-supplied.
98 * So when basedir is NULL and relpath is absolute, split it into its directory
99 * (trusted) and leaf and confine just the leaf -- exactly how secure_relative_
100 * open already trusts an absolute basedir while O_NOFOLLOW-confining the leaf.
101 * Anything else is a straight pass-through that preserves the strict contract. */
102 static int secure_basis_open(const char *basedir, const char *relpath, int flags, mode_t mode)
103 {
104 extern int am_daemon, am_chrooted;
105 extern unsigned int module_dirlen;
106
107 /* "insecure links = yes": restore the 3.2.7 plain open so an operator/peer
108 * alt-dest basis follows symlinks like legacy rsync, the same opt-out the
109 * other daemon symlink sites honour. */
110 if (symlink_optout_allowed()) {
111 if (basedir) {
112 char fullpath[MAXPATHLEN];
113 if (pathjoin(fullpath, sizeof fullpath, basedir, relpath) >= sizeof fullpath) {
114 errno = ENAMETOOLONG;
115 return -1;
116 }
117 return do_open(fullpath, flags, mode);
118 }
119 return do_open(relpath, flags, mode);
120 }
121
122 /* A peer-supplied --partial-dir basis/staging path (operator_path_resolve set
123 * by recv_files) may be absolute (module_dir-prefixed on a non-chroot daemon)
124 * and traverse a symlink the secure_relative_open path can't confine: resolve
125 * it with the ownership walk, which follows a uid0/euid-owned symlink but
126 * refuses a foreign one AND (via abspath_excluded_by_module) refuses a target
127 * the module's exclude hides -- closing the partial-dir exclude bypass. */
128 if (operator_path_resolve) {
129 char fullpath[MAXPATHLEN];
130 const char *p = relpath;
131 if (basedir) {
132 if (pathjoin(fullpath, sizeof fullpath, basedir, relpath) >= sizeof fullpath) {
133 errno = ENAMETOOLONG;
134 return -1;
135 }
136 p = fullpath;
137 }
138 return open_no_attacker_symlinks(p, flags, mode);
139 }
140
141 /* The confined resolver is needed for the sanitizing daemon
142 * (am_daemon && !am_chrooted) and for a /./ inner-module chroot
143 * (am_chrooted && module_dirlen) -- in the latter the kernel chroot confines
144 * only the outer path, so a peer-chosen alt-dest basis index (fnamecmp_type)
145 * could otherwise reach an outside-inner-module file through a symlinked
146 * parent. Local / remote-shell mode has no module boundary, and a plain
147 * "use chroot = yes" makes the kernel root the boundary, so there an alt-dest
148 * basis like --link-dest=../01 must resolve against the cwd as a bare open did
149 * before the hardening (confining it would reject the legitimate sibling
150 * "..", #915). The re-anchoring in secure_relative_open() covers the
151 * in-module ".." climb for the inner-module case too. */
152 if (!am_daemon || (am_chrooted && !module_dirlen)) {
153 if (basedir) {
154 char fullpath[MAXPATHLEN];
155 if (pathjoin(fullpath, sizeof fullpath, basedir, relpath) >= sizeof fullpath) {
156 errno = ENAMETOOLONG;
157 return -1;
158 }
159 return do_open(fullpath, flags, mode);
160 }
161 return do_open(relpath, flags, mode);
162 }
163
164 if (!basedir && relpath && *relpath == '/') {
165 const char *slash = strrchr(relpath, '/');
166 const char *leaf = slash + 1;
167 char dirbuf[MAXPATHLEN];
168 const char *dir;
169 if (slash == relpath)
170 dir = "/";
171 else {
172 size_t dlen = slash - relpath;
173 if (dlen >= sizeof dirbuf) {
174 errno = ENAMETOOLONG;
175 return -1;
176 }
177 memcpy(dirbuf, relpath, dlen);
178 dirbuf[dlen] = '\0';
179 dir = dirbuf;
180 }
181 return secure_relative_open(dir, leaf, flags, mode);
182 }
183 return secure_relative_open(basedir, relpath, flags, mode);
184 }
185
186 /* Keep the ownership policy for every attempt to open a one-inplace partial
187 * output. In particular, Linux's protected_regular compatibility retries
188 * must not downgrade an operator-path open to the ordinary path resolver. */
189 static int secure_recv_open(const char *path, int flags, mode_t mode, int owner_walk)
190 {
191 int fd, save = operator_path_resolve;
192
193 if (owner_walk)
194 operator_path_resolve = 1;
195 fd = secure_basis_open(NULL, path, flags, mode);
196 operator_path_resolve = save;
197 return fd;
198 }
199
200 /* Open a read-only regular file for an in-place update without leaving its
201 * mode relaxed while protocol data is received. Once a writable descriptor is
202 * open, later writes no longer depend on the pathname's permission bits, so
203 * restore the exact prior mode before returning to the transfer loop -- an
204 * abort (peer EOF, checksum failure, a signal) must not strand the file at
205 * 0600. Requires a regular file: O_NOFOLLOW refuses a symlink at the leaf but
206 * not a directory swapped in after the type probe. */
207 static int open_readonly_inplace(const char *fname, int one_inplace)
208 {
209 STRUCT_STAT cst;
210 mode_t prior_mode;
211 int cfd = -1, fd = -1;
212 int open_errno, restore_errno;
213
214 if (use_secure_symlinks || one_inplace) {
215 #ifdef O_NOFOLLOW
216 cfd = secure_recv_open(fname, O_RDONLY|O_NOFOLLOW, 0, one_inplace);
217 if (cfd < 0)
218 goto failed;
219 if (do_fstat(cfd, &cst) < 0 || !S_ISREG(cst.st_mode)) {
220 errno = EACCES; /* refused: not the read-only regular file we recover */
221 goto failed;
222 }
223 prior_mode = cst.st_mode & CHMOD_BITS;
224 if (prior_mode & S_IWUSR) {
225 /* Already owner-writable, so adding S_IWUSR cannot be what an
226 * EACCES is about (an ACL, or the parent dir). Don't touch the
227 * mode for nothing: each chmod risks losing a special bit. */
228 errno = EACCES;
229 goto failed;
230 }
231 if (fchmod(cfd, prior_mode | S_IWUSR) < 0)
232 goto failed;
233 fd = secure_recv_open(fname, O_WRONLY, 0600, one_inplace);
234 open_errno = errno;
235 if (fchmod(cfd, prior_mode) < 0) {
236 restore_errno = errno;
237 if (fd >= 0)
238 close(fd);
239 fd = -1;
240 open_errno = restore_errno;
241 }
242 close(cfd);
243 errno = open_errno;
244 return fd;
245 #else
246 /* Without O_NOFOLLOW the resolver's oldest fallback would follow a
247 * raced symlink, so fail closed rather than chmod through it. */
248 errno = EACCES;
249 return -1;
250 #endif
251 }
252
253 /* Local and chrooted transfers retain the existing pathname semantics.
254 * Note the S_ISREG test here is a type check on a stable path, NOT race
255 * protection: do_stat() follows a leaf symlink and each call below
256 * re-resolves the name. The fd-based branch above is the one that
257 * pins an inode; a chroot is what confines this one. */
258 if (do_stat(fname, &cst) < 0) {
259 errno = EACCES;
260 return -1;
261 }
262 if (!S_ISREG(cst.st_mode) || (cst.st_mode & CHMOD_BITS & S_IWUSR)) {
263 errno = EACCES;
264 return -1;
265 }
266 prior_mode = cst.st_mode & CHMOD_BITS;
267 if (do_chmod_at(fname, prior_mode | S_IWUSR) < 0)
268 return -1;
269 fd = do_open(fname, O_WRONLY, 0600);
270 open_errno = errno;
271 if (do_chmod_at(fname, prior_mode) < 0) {
272 restore_errno = errno;
273 if (fd >= 0)
274 close(fd);
275 fd = -1;
276 open_errno = restore_errno;
277 }
278 errno = open_errno;
279 return fd;
280
281 failed:
282 open_errno = errno;
283 if (cfd >= 0)
284 close(cfd);
285 errno = open_errno;
286 return -1;
287 }
288
289 /* get_tmpname() - create a tmp filename for a given filename
290 *
291 * If a tmpdir is defined, use that as the directory to put it in. Otherwise,
292 * the tmp filename is in the same directory as the given name. Note that
293 * there may be no directory at all in the given name!
294 *
295 * The tmp filename is basically the given filename with a dot prepended, and
296 * .XXXXXX appended (for mkstemp() to put its unique gunk in). We take care
297 * to not exceed either the MAXPATHLEN or NAME_MAX, especially the last, as
298 * the basename basically becomes 8 characters longer. In such a case, the
299 * original name is shortened sufficiently to make it all fit.
300 *
301 * If the make_unique arg is True, the XXXXXX string is replaced with a unique
302 * string that doesn't exist at the time of the check. This is intended to be
303 * used for creating hard links, symlinks, devices, and special files, since
304 * normal files should be handled by mkstemp() for safety.
305 *
306 * Of course, the only reason the file is based on the original name is to
307 * make it easier to figure out what purpose a temp file is serving when a
308 * transfer is in progress. */
309 int get_tmpname(char *fnametmp, const char *fname, BOOL make_unique)
310 {
311 int maxname, length = 0;
312 const char *f;
313 char *suf;
314
315 if (tmpdir) {
316 /* Note: this can't overflow, so the return value is safe */
317 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
318 fnametmp[length++] = '/';
319 }
320
321 if ((f = strrchr(fname, '/')) != NULL) {
322 ++f;
323 if (!tmpdir) {
324 length = f - fname;
325 /* copy up to and including the slash */
326 strlcpy(fnametmp, fname, length + 1);
327 }
328 } else
329 f = fname;
330
331 if (!tmpdir) { /* using a tmpdir avoids the leading dot on our temp names */
332 if (*f == '.') /* avoid an extra leading dot for OS X's sake */
333 f++;
334 fnametmp[length++] = '.';
335 }
336
337 /* The maxname value is bufsize, and includes space for the '\0'.
338 * NAME_MAX needs an extra -1 for the name's leading dot. */
339 maxname = MIN(MAXPATHLEN - length - TMPNAME_SUFFIX_LEN,
340 NAME_MAX - 1 - TMPNAME_SUFFIX_LEN);
341
342 if (maxname < 0) {
343 rprintf(FERROR_XFER, "temporary filename too long: %s\n", fname);
344 fnametmp[0] = '\0';
345 return 0;
346 }
347
348 if (maxname) {
349 int added = strlcpy(fnametmp + length, f, maxname);
350 if (added >= maxname)
351 added = maxname - 1;
352 suf = fnametmp + length + added;
353
354 /* Trim any dangling high-bit chars if the first-trimmed char (if any) is
355 * also a high-bit char, just in case we cut into a multi-byte sequence.
356 * We are guaranteed to stop because of the leading '.' we added. */
357 if ((int)f[added] & 0x80) {
358 while ((int)suf[-1] & 0x80)
359 suf--;
360 }
361 /* trim one trailing dot before our suffix's dot */
362 if (suf[-1] == '.')
363 suf--;
364 } else
365 suf = fnametmp + length - 1; /* overwrite the leading dot with suffix's dot */
366
367 if (make_unique) {
368 static unsigned counter_limit;
369 unsigned counter;
370
371 if (!counter_limit) {
372 counter_limit = (unsigned)getpid() + MAX_UNIQUE_LOOP;
373 if (counter_limit > MAX_UNIQUE_NUMBER || counter_limit < MAX_UNIQUE_LOOP)
374 counter_limit = MAX_UNIQUE_LOOP;
375 }
376 counter = counter_limit - MAX_UNIQUE_LOOP;
377
378 /* This doesn't have to be very good because we don't need
379 * to worry about someone trying to guess the values: all
380 * a conflict will do is cause a device, special file, hard
381 * link, or symlink to fail to be created. Also: avoid
382 * using mktemp() due to gcc's annoying warning. */
383 while (1) {
384 snprintf(suf, TMPNAME_SUFFIX_LEN+1, ".%d", counter);
385 if (access(fnametmp, 0) < 0)
386 break;
387 if (++counter >= counter_limit)
388 return 0;
389 }
390 } else
391 memcpy(suf, TMPNAME_SUFFIX, TMPNAME_SUFFIX_LEN+1);
392
393 return 1;
394 }
395
396 /* Opens a temporary file for writing.
397 * Success: Writes name into fnametmp, returns fd.
398 * Failure: Clobbers fnametmp, returns -1.
399 * Calling cleanup_set() is the caller's job. */
400 int open_tmpfile(char *fnametmp, const char *fname, struct file_struct *file)
401 {
402 int fd;
403 mode_t added_perms;
404
405 if (!get_tmpname(fnametmp, fname, False))
406 return -1;
407
408 if (am_root < 0) {
409 /* For --fake-super, the file must be useable by the copying
410 * user, just like it would be for root. */
411 added_perms = S_IRUSR|S_IWUSR;
412 } else {
413 /* For a normal copy, we need to be able to tweak things like xattrs. */
414 added_perms = S_IWUSR;
415 }
416
417 /* We initially set the perms without the setuid/setgid bits or group
418 * access to ensure that there is no race condition. They will be
419 * correctly updated after the right owner and group info is set.
420 * (Thanks to [email protected] for pointing this out.) */
421 /* For any non-chrooted receiver (secure_relpath_active()), create the
422 * temp file securely so a parent-symlink race can't redirect it. When
423 * the temp lives in the entry's own dir (the common case, no --temp-dir)
424 * use the cached held dir fd; otherwise fall back to secure_mkstemp. An
425 * operator-supplied --temp-dir (tmpdir) gets the ownership-walk resolver
426 * (it may legitimately point outside the tree); the deep-entry-dir fallback,
427 * when the held-dirfd cache declines, gets the strict transfer-path one. */
428 if (secure_relpath_active()) {
429 int dfd = held_dfd_for(fnametmp, file);
430 if (dfd >= 0) {
431 char *slash = strrchr(fnametmp, '/');
432 fd = do_mkstemp_atfd(dfd, slash ? slash + 1 : fnametmp,
433 (file->mode|added_perms) & INITACCESSPERMS);
434 } else
435 fd = secure_mkstemp(fnametmp, (file->mode|added_perms) & INITACCESSPERMS,
436 tmpdir != NULL);
437 } else
438 fd = do_mkstemp(fnametmp, (file->mode|added_perms) & INITACCESSPERMS);
439
440 #if 0
441 /* In most cases parent directories will already exist because their
442 * information should have been previously transferred, but that may
443 * not be the case with -R */
444 if (fd == -1 && relative_paths && errno == ENOENT
445 && make_path(fnametmp, MKP_SKIP_SLASH | MKP_DROP_NAME) == 0) {
446 /* Get back to name with XXXXXX in it. */
447 get_tmpname(fnametmp, fname, False);
448 fd = do_mkstemp(fnametmp, (file->mode|added_perms) & INITACCESSPERMS);
449 }
450 #endif
451
452 if (fd == -1) {
453 rsyserr(FERROR_XFER, errno, "mkstemp %s failed",
454 full_fname(fnametmp));
455 return -1;
456 }
457
458 return fd;
459 }
460
461 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
462 const char *fname, int fd, struct file_struct *file, int inplace_sizing)
463 {
464 static char file_sum1[MAX_DIGEST_LEN];
465 struct map_struct *mapbuf;
466 struct sum_struct sum;
467 int32 len;
468 OFF_T total_size = F_LENGTH(file);
469 OFF_T offset = 0;
470 OFF_T offset2;
471 char *data;
472 int32 i;
473 char *map = NULL;
474
475 #ifdef SUPPORT_PREALLOCATION
476 if (preallocate_files && fd != -1 && total_size > 0 && (!inplace_sizing || total_size > size_r)) {
477 /* Try to preallocate enough space for file's eventual length. Can
478 * reduce fragmentation on filesystems like ext4, xfs, and NTFS. */
479 if ((preallocated_len = do_fallocate(fd, 0, total_size)) < 0)
480 rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(fname));
481 } else
482 #endif
483 if (inplace_sizing) {
484 #ifdef HAVE_FTRUNCATE
485 /* The most compatible way to create a sparse file is to start with no length. */
486 if (sparse_files > 0 && whole_file && fd >= 0 && do_ftruncate(fd, 0) == 0)
487 preallocated_len = 0;
488 else
489 #endif
490 preallocated_len = size_r;
491 } else
492 preallocated_len = 0;
493
494 read_sum_head(f_in, &sum);
495
496 if (fd_r >= 0 && size_r > 0) {
497 int32 read_size = MAX(sum.blength * 2, 16*1024);
498 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
499 if (DEBUG_GTE(DELTASUM, 2)) {
500 rprintf(FINFO, "recv mapped %s of size %s\n",
501 fname_r, big_num(size_r));
502 }
503 } else
504 mapbuf = NULL;
505
506 sum_init(xfer_sum_nni, checksum_seed);
507
508 if (append_mode > 0) {
509 OFF_T j;
510 sum.flength = (OFF_T)sum.count * sum.blength;
511 if (sum.remainder)
512 sum.flength -= sum.blength - sum.remainder;
513 if (append_mode == 2 && mapbuf) {
514 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
515 if (INFO_GTE(PROGRESS, 1))
516 show_progress(offset, total_size);
517 sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
518 CHUNK_SIZE);
519 offset = j;
520 }
521 if (offset < sum.flength) {
522 int32 len = (int32)(sum.flength - offset);
523 if (INFO_GTE(PROGRESS, 1))
524 show_progress(offset, total_size);
525 sum_update(map_ptr(mapbuf, offset, len), len);
526 }
527 }
528 offset = sum.flength;
529 if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) {
530 rsyserr(FERROR_XFER, errno, "lseek of %s returned %s, not %s",
531 full_fname(fname), big_num(j), big_num(offset));
532 exit_cleanup(RERR_FILEIO);
533 }
534 }
535
536 while (1) {
537 data = NULL;
538 i = recv_token(f_in, &data);
539 if (i == 0)
540 break;
541
542 if (INFO_GTE(PROGRESS, 1))
543 show_progress(offset, total_size);
544
545 if (allowed_lull)
546 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH | MSK_ACTIVE_RECEIVER);
547
548 if (i > 0) {
549 if (!data) {
550 rprintf(FERROR, "Invalid literal token with no data [%s]\n", who_am_i());
551 exit_cleanup(RERR_PROTOCOL);
552 }
553 if (DEBUG_GTE(DELTASUM, 3)) {
554 rprintf(FINFO,"data recv %d at %s\n",
555 i, big_num(offset));
556 }
557
558 stats.literal_data += i;
559 cleanup_got_literal = 1;
560
561 sum_update(data, i);
562
563 if (fd != -1 && write_file(fd, 0, offset, data, i) != i)
564 goto report_write_error;
565 offset += i;
566 continue;
567 }
568
569 i = -(i+1);
570 if (i < 0 || i >= sum.count) {
571 rprintf(FERROR, "Invalid block index %d (count=%ld) [%s]\n",
572 i, (long)sum.count, who_am_i());
573 exit_cleanup(RERR_PROTOCOL);
574 }
575 offset2 = i * (OFF_T)sum.blength;
576 len = sum.blength;
577 if (i == (int)sum.count-1 && sum.remainder != 0)
578 len = sum.remainder;
579
580 stats.matched_data += len;
581
582 /* A block match with no mapped basis is a protocol inconsistency
583 * ONLY when we are actually producing output (fd != -1): the
584 * generator told the sender a basis existed but the receiver could
585 * not open it, so honoring the match would silently omit these
586 * bytes from the verification checksum (a spurious failure) or
587 * leave a hole in the output. Fail cleanly in that case.
588 *
589 * On the DISCARD path (fd == -1, fname == NULL) there is no output
590 * and no verification: discard_receive_data() deliberately drains a
591 * delta the receiver never intends to write (basis fstat failed,
592 * basis is a directory, output open failed, batch skip, ...). The
593 * sender does not know the data is being discarded and streams an
594 * ordinary delta, so a match token here is NORMAL protocol, not
595 * malformed. Absorb it benignly (advance the offset and continue),
596 * as the pre-existing "if (mapbuf)" guards did before this check was
597 * added in 31fbb17d -- erroring would wrongly break legitimate
598 * transfers, and full_fname(fname) with fname==NULL would
599 * dereference NULL (a receiver crash on a normal transfer). */
600 if (!mapbuf) {
601 if (fd != -1) {
602 rprintf(FERROR, "got a block match with no basis file for %s [%s]\n",
603 full_fname(fname), who_am_i());
604 exit_cleanup(RERR_PROTOCOL);
605 }
606 offset += len;
607 continue;
608 }
609
610 if (DEBUG_GTE(DELTASUM, 3)) {
611 rprintf(FINFO,
612 "chunk[%d] of size %ld at %s offset=%s%s\n",
613 i, (long)len, big_num(offset2), big_num(offset),
614 updating_basis_or_equiv && offset == offset2 ? " (seek)" : "");
615 }
616
617 if (mapbuf) {
618 map = map_ptr(mapbuf,offset2,len);
619
620 see_token(map, len);
621 sum_update(map, len);
622 }
623
624 if (updating_basis_or_equiv) {
625 if (offset == offset2 && fd != -1) {
626 if (skip_matched(fd, offset, map, len) < 0)
627 goto report_write_error;
628 offset += len;
629 continue;
630 }
631 }
632 if (fd != -1 && map && write_file(fd, 0, offset, map, len) != (int)len)
633 goto report_write_error;
634 offset += len;
635 }
636
637 if (fd != -1 && offset > 0) {
638 if (sparse_files > 0) {
639 if (sparse_end(fd, offset, updating_basis_or_equiv) != 0)
640 goto report_write_error;
641 } else if (flush_write_file(fd) < 0) {
642 report_write_error:
643 rsyserr(FERROR_XFER, errno, "write failed on %s", full_fname(fname));
644 exit_cleanup(RERR_FILEIO);
645 }
646 }
647
648 #ifdef HAVE_FTRUNCATE
649 /* inplace: New data could be shorter than old data.
650 * preallocate_files: total_size could have been an overestimate.
651 * Cut off any extra preallocated zeros from dest file. */
652 if ((inplace_sizing || preallocated_len > offset) && fd != -1 && !IS_DEVICE(file->mode)) {
653 if (do_ftruncate(fd, offset) < 0)
654 rsyserr(FERROR_XFER, errno, "ftruncate failed on %s", full_fname(fname));
655 }
656 #endif
657
658 if (INFO_GTE(PROGRESS, 1))
659 end_progress(total_size);
660
661 sum_end(file_sum1);
662
663 if (do_fsync && fd != -1 && fsync(fd) != 0) {
664 rsyserr(FERROR, errno, "fsync failed on %s", full_fname(fname));
665 exit_cleanup(RERR_FILEIO);
666 }
667
668 if (mapbuf)
669 unmap_file(mapbuf);
670
671 read_buf(f_in, sender_file_sum, xfer_sum_len);
672 if (DEBUG_GTE(DELTASUM, 2))
673 rprintf(FINFO,"got file_sum\n");
674 if (fd != -1 && memcmp(file_sum1, sender_file_sum, xfer_sum_len) != 0)
675 return 0;
676 return 1;
677 }
678
679
680 static void discard_receive_data(int f_in, struct file_struct *file)
681 {
682 receive_data(f_in, NULL, -1, 0, NULL, -1, file, 0);
683 }
684
685 static void handle_delayed_updates(char *local_name)
686 {
687 char *fname, *partialptr;
688 int ndx;
689
690 for (ndx = -1; (ndx = bitbag_next_bit(delayed_bits, ndx)) >= 0; ) {
691 struct file_struct *file = cur_flist->files[ndx];
692 fname = local_name ? local_name : f_name(file, NULL);
693 if ((partialptr = partial_dir_fname(fname)) != NULL) {
694 if (make_backups > 0 && !make_backup(fname, False))
695 continue;
696 if (DEBUG_GTE(RECV, 1)) {
697 rprintf(FINFO, "renaming %s to %s\n",
698 partialptr, fname);
699 }
700 /* We don't use robust_rename() here because the
701 * partial-dir must be on the same drive. Resolve the
702 * --partial-dir source through the exclude-aware ownership
703 * walk so a symlinked partial-dir can't move a file out of
704 * an excluded subtree. */
705 int rret;
706 operator_path_resolve = 1;
707 rret = do_rename_at(partialptr, fname);
708 operator_path_resolve = 0;
709 if (rret < 0) {
710 rsyserr(FERROR_XFER, errno,
711 "rename failed for %s (from %s)",
712 full_fname(fname), partialptr);
713 } else {
714 if (remove_source_files || (preserve_hard_links && F_IS_HLINKED(file)))
715 send_msg_success(fname, ndx);
716 handle_partial_dir(partialptr, PDIR_DELETE);
717 }
718 }
719 }
720 }
721
722 static void no_batched_update(int ndx, BOOL is_redo)
723 {
724 struct file_list *flist = flist_for_ndx(ndx, "no_batched_update");
725 struct file_struct *file;
726 if (ndx < flist->ndx_start)
727 exit_cleanup(RERR_PROTOCOL);
728 file = flist->files[ndx - flist->ndx_start];
729
730 rprintf(FERROR_XFER, "(No batched update for%s \"%s\")\n",
731 is_redo ? " resend of" : "", f_name(file, NULL));
732
733 if (inc_recurse && !dry_run)
734 send_msg_int(MSG_NO_SEND, ndx);
735 }
736
737 static int we_want_redo(int desired_ndx)
738 {
739 static int redo_ndx = -1;
740
741 while (redo_ndx < desired_ndx) {
742 if (redo_ndx >= 0)
743 no_batched_update(redo_ndx, True);
744 if ((redo_ndx = flist_ndx_pop(&batch_redo_list)) < 0)
745 return 0;
746 }
747
748 if (redo_ndx == desired_ndx) {
749 redo_ndx = -1;
750 return 1;
751 }
752
753 return 0;
754 }
755
756 static int gen_wants_ndx(int desired_ndx, int flist_num)
757 {
758 static int next_ndx = -1;
759 static int done_cnt = 0;
760 static BOOL got_eof = False;
761
762 if (got_eof)
763 return 0;
764
765 /* TODO: integrate gen-reading I/O into perform_io() so this is not needed? */
766 io_flush(FULL_FLUSH);
767
768 while (next_ndx < desired_ndx) {
769 if (inc_recurse && flist_num <= done_cnt)
770 return 0;
771 if (next_ndx >= 0)
772 no_batched_update(next_ndx, False);
773 if ((next_ndx = read_int(batch_gen_fd)) < 0) {
774 if (inc_recurse) {
775 done_cnt++;
776 continue;
777 }
778 got_eof = True;
779 return 0;
780 }
781 }
782
783 if (next_ndx == desired_ndx) {
784 next_ndx = -1;
785 return 1;
786 }
787
788 return 0;
789 }
790
791 /**
792 * main routine for receiver process.
793 *
794 * Receiver process runs on the same host as the generator process. */
795 int recv_files(int f_in, int f_out, char *local_name)
796 {
797 int fd1,fd2;
798 STRUCT_STAT st;
799 int iflags, xlen;
800 char *fname, fbuf[MAXPATHLEN];
801 char xname[MAXPATHLEN];
802 char *fnametmp, fnametmpbuf[MAXPATHLEN];
803 char *fnamecmp, *partialptr;
804 char fnamecmpbuf[MAXPATHLEN];
805 uchar fnamecmp_type;
806 struct file_struct *file;
807 int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
808 enum logcode log_code = log_before_transfer ? FLOG : FINFO;
809 int max_phase = protocol_version >= 29 ? 2 : 1;
810 int dflt_perms = (ACCESSPERMS & ~orig_umask);
811 #ifdef SUPPORT_ACLS
812 const char *parent_dirname = "";
813 #endif
814 int ndx, recv_ok, one_inplace, write_to_device;
815 mode_t write_devices_saved_mode = 0;
816
817 if (DEBUG_GTE(RECV, 1))
818 rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used);
819
820 if (delay_updates)
821 delayed_bits = bitbag_create(cur_flist->used + 1);
822
823 if (whole_file < 0)
824 whole_file = 0;
825
826 progress_init();
827
828 while (1) {
829 const char *basedir = NULL;
830
831 cleanup_disable();
832
833 /* This call also sets cur_flist. */
834 ndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type,
835 xname, &xlen);
836 if (ndx == NDX_DONE) {
837 if (!am_server && cur_flist) {
838 set_current_file_index(NULL, 0);
839 if (INFO_GTE(PROGRESS, 2))
840 end_progress(0);
841 }
842 if (inc_recurse && first_flist) {
843 if (read_batch) {
844 ndx = first_flist->used + first_flist->ndx_start;
845 gen_wants_ndx(ndx, first_flist->flist_num);
846 }
847 flist_free(first_flist);
848 if (first_flist)
849 continue;
850 } else if (read_batch && first_flist) {
851 ndx = first_flist->used;
852 gen_wants_ndx(ndx, first_flist->flist_num);
853 }
854 if (++phase > max_phase)
855 break;
856 if (DEBUG_GTE(RECV, 1))
857 rprintf(FINFO, "recv_files phase=%d\n", phase);
858 if (phase == 2 && delay_updates)
859 handle_delayed_updates(local_name);
860 write_int(f_out, NDX_DONE);
861 continue;
862 }
863
864 if (ndx - cur_flist->ndx_start >= 0)
865 file = cur_flist->files[ndx - cur_flist->ndx_start];
866 else if (cur_flist->parent_ndx < 0
867 || cur_flist->parent_ndx >= dir_flist->used)
868 exit_cleanup(RERR_PROTOCOL);
869 else
870 file = dir_flist->files[cur_flist->parent_ndx];
871 if (!F_IS_ACTIVE(file)) {
872 /* A peer that sends duplicate file-list entries gets
873 * one of them clear_file()'d by flist_sort_and_clean();
874 * referencing that slot here yields fname == NULL and
875 * a crash in the first deref (daemon filter check,
876 * set_file_attrs → full_fname, …). */
877 rprintf(FERROR,
878 "rsync: refusing transfer of cleared file index %d\n",
879 ndx);
880 exit_cleanup(RERR_PROTOCOL);
881 }
882 fname = local_name ? local_name : f_name(file, fbuf);
883
884 if (DEBUG_GTE(RECV, 1))
885 rprintf(FINFO, "recv_files(%s)\n", fname);
886
887 if (daemon_filter_list.head && (*fname != '.' || fname[1] != '\0')) {
888 int filt_flags = S_ISDIR(file->mode) ? NAME_IS_DIR : NAME_IS_FILE;
889 if (check_filter(&daemon_filter_list, FLOG, fname, filt_flags) < 0) {
890 rprintf(FERROR, "ERROR: rejecting file transfer request for daemon excluded file: %s\n",
891 fname);
892 exit_cleanup(RERR_PROTOCOL);
893 }
894 }
895
896 #ifdef SUPPORT_XATTRS
897 if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
898 && !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)))
899 recv_xattr_request(file, f_in);
900 #endif
901
902 if (!(iflags & ITEM_TRANSFER)) {
903 maybe_log_item(file, iflags, itemizing, xname);
904 #ifdef SUPPORT_XATTRS
905 if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
906 && !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))
907 set_file_attrs(fname, file, NULL, fname, 0);
908 #endif
909 if (iflags & ITEM_IS_NEW) {
910 stats.created_files++;
911 if (S_ISREG(file->mode)) {
912 /* Nothing further to count. */
913 } else if (S_ISDIR(file->mode))
914 stats.created_dirs++;
915 #ifdef SUPPORT_LINKS
916 else if (S_ISLNK(file->mode))
917 stats.created_symlinks++;
918 #endif
919 else if (IS_DEVICE(file->mode))
920 stats.created_devices++;
921 else
922 stats.created_specials++;
923 }
924 continue;
925 }
926 if (phase == 2) {
927 rprintf(FERROR,
928 "got transfer request in phase 2 [%s]\n",
929 who_am_i());
930 exit_cleanup(RERR_PROTOCOL);
931 }
932
933 if (file->flags & FLAG_FILE_SENT) {
934 if (csum_length == SHORT_SUM_LENGTH) {
935 if (keep_partial && !partial_dir)
936 make_backups = -make_backups; /* prevents double backup */
937 if (append_mode)
938 sparse_files = -sparse_files;
939 append_mode = -append_mode;
940 csum_length = SUM_LENGTH;
941 redoing = 1;
942 }
943 } else {
944 if (csum_length != SHORT_SUM_LENGTH) {
945 if (keep_partial && !partial_dir)
946 make_backups = -make_backups;
947 if (append_mode)
948 sparse_files = -sparse_files;
949 append_mode = -append_mode;
950 csum_length = SHORT_SUM_LENGTH;
951 redoing = 0;
952 }
953 if (iflags & ITEM_IS_NEW)
954 stats.created_files++;
955 }
956
957 if (!am_server)
958 set_current_file_index(file, ndx);
959 stats.xferred_files++;
960 stats.total_transferred_size += F_LENGTH(file);
961
962 cleanup_got_literal = 0;
963
964 if (read_batch) {
965 int wanted = redoing
966 ? we_want_redo(ndx)
967 : gen_wants_ndx(ndx, cur_flist->flist_num);
968 if (!wanted) {
969 rprintf(FINFO,
970 "(Skipping batched update for%s \"%s\")\n",
971 redoing ? " resend of" : "",
972 fname);
973 discard_receive_data(f_in, file);
974 file->flags |= FLAG_FILE_SENT;
975 continue;
976 }
977 }
978
979 remember_initial_stats();
980
981 if (!do_xfers) { /* log the transfer */
982 log_item(FCLIENT, file, iflags, NULL);
983 if (read_batch)
984 discard_receive_data(f_in, file);
985 continue;
986 }
987 if (write_batch < 0) {
988 log_item(FCLIENT, file, iflags, NULL);
989 if (!am_server)
990 discard_receive_data(f_in, file);
991 if (inc_recurse)
992 send_msg_success(fname, ndx);
993 continue;
994 }
995
996 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
997
998 if (protocol_version >= 29) {
999 switch (fnamecmp_type) {
1000 case FNAMECMP_FNAME:
1001 fnamecmp = fname;
1002 break;
1003 case FNAMECMP_PARTIAL_DIR:
1004 fnamecmp = partialptr;
1005 break;
1006 case FNAMECMP_BACKUP:
1007 fnamecmp = get_backup_name(fname);
1008 break;
1009 case FNAMECMP_FUZZY:
1010 if (fuzzy_basis == 0) {
1011 rprintf(FERROR_XFER, "rsync: refusing malicious fuzzy operation for %s\n", xname);
1012 exit_cleanup(RERR_PROTOCOL);
1013 }
1014 if (file->dirname) {
1015 basedir = file->dirname;
1016 }
1017 fnamecmp = xname;
1018 break;
1019 default:
1020 if (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) {
1021 fnamecmp_type -= FNAMECMP_FUZZY + 1;
1022 if (file->dirname) {
1023 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], file->dirname);
1024 basedir = fnamecmpbuf;
1025 } else {
1026 basedir = basis_dir[fnamecmp_type];
1027 }
1028 fnamecmp = xname;
1029 } else if (fnamecmp_type >= basis_dir_cnt) {
1030 rprintf(FERROR,
1031 "invalid basis_dir index: %d.\n",
1032 fnamecmp_type);
1033 exit_cleanup(RERR_PROTOCOL);
1034 } else {
1035 basedir = basis_dir[fnamecmp_type];
1036 fnamecmp = fname;
1037 }
1038 break;
1039 }
1040 if (!fnamecmp || (daemon_filter_list.head
1041 && check_filter(&daemon_filter_list, FLOG, fnamecmp, 0) < 0)) {
1042 fnamecmp = fname;
1043 fnamecmp_type = FNAMECMP_FNAME;
1044 }
1045 } else {
1046 /* Reminder: --inplace && --partial-dir are never
1047 * enabled at the same time. */
1048 if (inplace && make_backups > 0) {
1049 if (!(fnamecmp = get_backup_name(fname)))
1050 fnamecmp = fname;
1051 else
1052 fnamecmp_type = FNAMECMP_BACKUP;
1053 } else if (partial_dir && partialptr)
1054 fnamecmp = partialptr;
1055 else
1056 fnamecmp = fname;
1057 }
1058
1059 /* Open the delta basis. When it lives in the entry's own dir (no
1060 * alternate basedir), read it via the held dir fd with O_NOFOLLOW: a
1061 * regular-file basis is never legitimately a symlink, and refusing a
1062 * planted one avoids both an escape and a basis-content info-leak.
1063 * Otherwise use secure_basis_open, which also tolerates an operator-
1064 * trusted absolute fnamecmp (e.g. an absolute --partial-dir basis). */
1065 {
1066 int bdfd;
1067 if (fnamecmp_type == FNAMECMP_PARTIAL_DIR
1068 && fnamecmp && *fnamecmp != '/') {
1069 /* The relative partial path contains peer-derived directory
1070 * components. It is not an operator-trusted path as a whole. */
1071 fd1 = secure_relative_open(NULL, fnamecmp, O_RDONLY, 0);
1072 } else if (!basedir && (bdfd = held_dfd_for(fnamecmp, file)) >= 0) {
1073 const char *slash;
1074 assert(fnamecmp != NULL); /* set on every path above */
1075 slash = strrchr(fnamecmp, '/');
1076 fd1 = do_open_atfd(bdfd, slash ? slash + 1 : fnamecmp, O_RDONLY, 0);
1077 } else {
1078 /* An operator-supplied basis -- a --partial-dir, or an
1079 * alt-dest basedir (--copy-dest/--compare-dest/--link-dest) --
1080 * is a peer/operator path: resolve it with the exclude-aware
1081 * ownership walk so a flipped foreign-owned parent symlink can't
1082 * read (and feed back as delta) an out-of-tree / excluded file.
1083 * The walk still allows the legitimate "../sibling" basis (#915)
1084 * and the operator's own uid0/euid symlinks. A daemon keeps its
1085 * stronger confinement branch in secure_basis_open(), so only
1086 * route the alt-dest basedir read through the walk off-daemon. */
1087 if ((basedir && !am_daemon) || fnamecmp_type == FNAMECMP_PARTIAL_DIR)
1088 operator_path_resolve = 1;
1089 fd1 = secure_basis_open(basedir, fnamecmp, O_RDONLY, 0);
1090 operator_path_resolve = 0;
1091 }
1092 }
1093 if (fnamecmp_type == FNAMECMP_PARTIAL_DIR && fd1 == -1) {
1094 /* The sender may claim a partial basis even when the generator's
1095 * confined lookup rejected it. Drop that path as the delta basis
1096 * and in-place output target. A daemon that negotiated in-place
1097 * partial updates rejects the unsafe peer option; otherwise (a pre-30
1098 * peer, where no in-place partial redirect is possible, or a pull
1099 * client) fall back to a safe no-basis update. */
1100 if (am_daemon && inplace_partial) {
1101 rprintf(FERROR,
1102 "rsync: refusing unconfined partial basis for %s\n", fname);
1103 exit_cleanup(RERR_PROTOCOL);
1104 }
1105 fnamecmp = fname;
1106 fnamecmp_type = FNAMECMP_FNAME;
1107 }
1108
1109 if (fd1 == -1 && protocol_version < 29) {
1110 if (fnamecmp != fname) {
1111 fnamecmp = fname;
1112 fnamecmp_type = FNAMECMP_FNAME;
1113 fd1 = do_open_nofollow(fnamecmp, O_RDONLY);
1114 }
1115
1116 if (fd1 == -1 && basis_dir[0]) {
1117 /* pre-29 allowed only one alternate basis */
1118 basedir = basis_dir[0];
1119 fnamecmp = fname;
1120 fnamecmp_type = FNAMECMP_BASIS_DIR_LOW;
1121 if (!am_daemon)
1122 operator_path_resolve = 1;
1123 fd1 = secure_basis_open(basedir, fnamecmp, O_RDONLY, 0);
1124 operator_path_resolve = 0;
1125 }
1126 }
1127
1128 if (basedir) {
1129 // for the following code we need the full
1130 // path name as a single string
1131 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basedir, fnamecmp);
1132 fnamecmp = fnamecmpbuf;
1133 }
1134
1135 /* A peer's basis selector cannot enable direct output through a path
1136 * that the confined basis open did not validate. */
1137 one_inplace = inplace_partial && fnamecmp_type == FNAMECMP_PARTIAL_DIR
1138 && fd1 != -1;
1139 updating_basis_or_equiv = one_inplace
1140 || (inplace && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP));
1141
1142 if (fd1 == -1) {
1143 st.st_mode = 0;
1144 st.st_size = 0;
1145 } else if (do_fstat(fd1,&st) != 0) {
1146 rsyserr(FERROR_XFER, errno, "fstat %s failed",
1147 full_fname(fnamecmp));
1148 discard_receive_data(f_in, file);
1149 close(fd1);
1150 if (inc_recurse)
1151 send_msg_int(MSG_NO_SEND, ndx);
1152 continue;
1153 }
1154
1155 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
1156 /* this special handling for directories
1157 * wouldn't be necessary if robust_rename()
1158 * and the underlying robust_unlink could cope
1159 * with directories
1160 */
1161 rprintf(FERROR_XFER, "recv_files: %s is a directory\n",
1162 full_fname(fnamecmp));
1163 discard_receive_data(f_in, file);
1164 close(fd1);
1165 if (inc_recurse)
1166 send_msg_int(MSG_NO_SEND, ndx);
1167 continue;
1168 }
1169
1170 write_to_device = write_devices && IS_DEVICE(st.st_mode);
1171 if (write_to_device) {
1172 if (fd1 != -1 && st.st_size == 0)
1173 st.st_size = get_device_size(fd1, fname);
1174 } else if (fd1 != -1 && !(S_ISREG(st.st_mode))) {
1175 close(fd1);
1176 fd1 = -1;
1177 }
1178
1179 /* If we're not preserving permissions, change the file-list's
1180 * mode based on the local permissions and some heuristics. */
1181 if (!preserve_perms) {
1182 int exists = fd1 != -1;
1183 #ifdef SUPPORT_ACLS
1184 const char *dn = file->dirname ? file->dirname : ".";
1185 if (parent_dirname != dn
1186 && strcmp(parent_dirname, dn) != 0) {
1187 dflt_perms = default_perms_for_dir(dn);
1188 parent_dirname = dn;
1189 }
1190 #endif
1191 file->mode = dest_mode(file->mode, st.st_mode, dflt_perms, exists);
1192 }
1193
1194 /* We now check to see if we are writing the file "inplace" */
1195 if (inplace || one_inplace) {
1196 fnametmp = one_inplace ? partialptr : fname;
1197 /* For any non-chrooted receiver (secure_relpath_active()),
1198 * use secure open to prevent symlink race attacks where an
1199 * attacker could switch a directory to a symlink between
1200 * path validation and file open. */
1201 /* one_inplace stages into the operator/peer --partial-dir path:
1202 * resolve it with the ownership walk (exclude-aware) so it can't be
1203 * redirected through a symlink into an excluded subtree. */
1204 if (secure_relpath_active())
1205 fd2 = secure_recv_open(fnametmp, O_WRONLY|O_CREAT, 0600,
1206 one_inplace);
1207 else
1208 fd2 = do_open(fnametmp, O_WRONLY|O_CREAT, 0600);
1209 #ifdef linux
1210 if (fd2 == -1 && errno == EACCES) {
1211 /* Maybe the error was due to protected_regular setting? */
1212 if (use_secure_symlinks || one_inplace)
1213 fd2 = secure_recv_open(fnametmp, O_WRONLY, 0600,
1214 one_inplace);
1215 else
1216 fd2 = do_open(fnametmp, O_WRONLY, 0600);
1217 }
1218 #endif
1219 if (fd2 == -1 && errno == EACCES) {
1220 /* Temporarily add owner-write access only long enough to open
1221 * a writable descriptor; the helper restores the old mode
1222 * before any network data is consumed, including on failure. */
1223 fd2 = open_readonly_inplace(fnametmp, one_inplace);
1224 }
1225 if (fd2 == -1) {
1226 rsyserr(FERROR_XFER, errno, "open %s failed",
1227 full_fname(fnametmp));
1228 } else if (updating_basis_or_equiv)
1229 cleanup_set(NULL, NULL, file, fd1, fd2);
1230 } else {
1231 fnametmp = fnametmpbuf;
1232 fd2 = open_tmpfile(fnametmp, fname, file);
1233 if (fd2 != -1)
1234 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
1235 }
1236
1237 if (fd2 == -1) {
1238 discard_receive_data(f_in, file);
1239 if (fd1 != -1)
1240 close(fd1);
1241 if (inc_recurse)
1242 send_msg_int(MSG_NO_SEND, ndx);
1243 continue;
1244 }
1245
1246 /* log the transfer */
1247 if (log_before_transfer)
1248 log_item(FCLIENT, file, iflags, NULL);
1249 else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))
1250 rprintf(FINFO, "%s\n", fname);
1251
1252 /* --write-devices writes a regular source file's content into an
1253 * existing destination device. Flip file->mode to S_IFBLK just for
1254 * receive_data()'s ftruncate gate (!IS_DEVICE), then restore it right
1255 * after -- the file_struct was built as a regular file with no
1256 * DEV_EXTRA_CNT, so leaving it S_IFBLK would make set_stat_xattr's
1257 * F_RDEV_P() read past the allocation. Kept tight here (after the
1258 * pre-transfer log and the fd2 bail-out) so no continue skips the
1259 * restore and dest_mode() above ran on the real mode. */
1260 if (write_to_device) {
1261 write_devices_saved_mode = file->mode;
1262 file->mode = S_IFBLK | (file->mode & ACCESSPERMS);
1263 }
1264
1265 /* recv file data */
1266 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size, fname, fd2, file, inplace || one_inplace);
1267
1268 if (write_to_device) {
1269 file->mode = write_devices_saved_mode;
1270 write_devices_saved_mode = 0;
1271 }
1272
1273 log_item(log_code, file, iflags, NULL);
1274 if (want_progress_now)
1275 instant_progress(fname);
1276
1277 if (fd1 != -1)
1278 close(fd1);
1279 if (close(fd2) < 0) {
1280 rsyserr(FERROR, errno, "close failed on %s",
1281 full_fname(fnametmp));
1282 exit_cleanup(RERR_FILEIO);
1283 }
1284
1285 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
1286 if (partialptr == fname)
1287 partialptr = NULL;
1288 if (!finish_transfer(fname, fnametmp, fnamecmp, partialptr, file, recv_ok, 1))
1289 recv_ok = -1;
1290 else if (fnamecmp == partialptr) {
1291 if (!one_inplace) {
1292 /* Unlink the consumed --partial-dir basis through the
1293 * exclude-aware ownership walk (a symlinked partial-dir
1294 * must not delete a file in an excluded subtree). */
1295 operator_path_resolve = 1;
1296 do_unlink_at(partialptr);
1297 operator_path_resolve = 0;
1298 }
1299 handle_partial_dir(partialptr, PDIR_DELETE);
1300 }
1301 } else if (keep_partial && partialptr && (!one_inplace || delay_updates)) {
1302 if (!handle_partial_dir(partialptr, PDIR_CREATE)) {
1303 rprintf(FERROR,
1304 "Unable to create partial-dir for %s -- discarding %s.\n",
1305 local_name ? local_name : f_name(file, NULL),
1306 recv_ok ? "completed file" : "partial file");
1307 do_unlink_at(fnametmp);
1308 recv_ok = -1;
1309 } else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,
1310 file, recv_ok, !partial_dir))
1311 recv_ok = -1;
1312 else if (delay_updates && recv_ok) {
1313 bitbag_set_bit(delayed_bits, ndx);
1314 recv_ok = 2;
1315 } else
1316 partialptr = NULL;
1317 } else if (!one_inplace)
1318 do_unlink_at(fnametmp);
1319
1320 cleanup_disable();
1321
1322 if (read_batch)
1323 file->flags |= FLAG_FILE_SENT;
1324
1325 switch (recv_ok) {
1326 case 2:
1327 break;
1328 case 1:
1329 if (remove_source_files || inc_recurse || (preserve_hard_links && F_IS_HLINKED(file)))
1330 send_msg_success(fname, ndx);
1331 break;
1332 case 0: {
1333 enum logcode msgtype = redoing ? FERROR_XFER : FWARNING;
1334 if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1) || stdout_format_has_i) {
1335 char *errstr, *redostr, *keptstr;
1336 if (!(keep_partial && partialptr) && !inplace)
1337 keptstr = "discarded";
1338 else if (partial_dir)
1339 keptstr = "put into partial-dir";
1340 else
1341 keptstr = "retained";
1342 if (msgtype == FERROR_XFER) {
1343 errstr = "ERROR";
1344 redostr = "";
1345 } else {
1346 errstr = "WARNING";
1347 redostr = read_batch ? " (may try again)"
1348 : " (will try again)";
1349 }
1350 rprintf(msgtype,
1351 "%s: %s failed verification -- update %s%s.\n",
1352 errstr, local_name ? f_name(file, NULL) : fname,
1353 keptstr, redostr);
1354 }
1355 if (!redoing) {
1356 if (read_batch)
1357 flist_ndx_push(&batch_redo_list, ndx);
1358 send_msg_int(MSG_REDO, ndx);
1359 file->flags |= FLAG_FILE_SENT;
1360 } else if (inc_recurse)
1361 send_msg_int(MSG_NO_SEND, ndx);
1362 break;
1363 }
1364 case -1:
1365 if (inc_recurse)
1366 send_msg_int(MSG_NO_SEND, ndx);
1367 break;
1368 }
1369 }
1370 if (make_backups < 0)
1371 make_backups = -make_backups;
1372
1373 if (phase == 2 && delay_updates) /* for protocol_version < 29 */
1374 handle_delayed_updates(local_name);
1375
1376 if (DEBUG_GTE(RECV, 1))
1377 rprintf(FINFO,"recv_files finished\n");
1378
1379 return 0;
1380 }