Preparing for release of 3.1.0
[rsync.git] / receiver.c
blob1e064d9dd65a02da9946992fb1ced98683a86d1c
1 /*
2 * Routines only used by the receiving process.
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2013 Wayne Davison
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.
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.
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.
22 #include "rsync.h"
23 #include "inums.h"
25 extern int dry_run;
26 extern int do_xfers;
27 extern int am_root;
28 extern int am_server;
29 extern int inc_recurse;
30 extern int log_before_transfer;
31 extern int stdout_format_has_i;
32 extern int logfile_format_has_i;
33 extern int csum_length;
34 extern int read_batch;
35 extern int write_batch;
36 extern int batch_gen_fd;
37 extern int protocol_version;
38 extern int relative_paths;
39 extern int preserve_hard_links;
40 extern int preserve_perms;
41 extern int preserve_xattrs;
42 extern int basis_dir_cnt;
43 extern int make_backups;
44 extern int cleanup_got_literal;
45 extern int remove_source_files;
46 extern int append_mode;
47 extern int sparse_files;
48 extern int preallocate_files;
49 extern int keep_partial;
50 extern int checksum_len;
51 extern int checksum_seed;
52 extern int inplace;
53 extern int allowed_lull;
54 extern int delay_updates;
55 extern mode_t orig_umask;
56 extern struct stats stats;
57 extern char *tmpdir;
58 extern char *partial_dir;
59 extern char *basis_dir[MAX_BASIS_DIRS+1];
60 extern char sender_file_sum[MAX_DIGEST_LEN];
61 extern struct file_list *cur_flist, *first_flist, *dir_flist;
62 extern filter_rule_list daemon_filter_list;
64 static struct bitbag *delayed_bits = NULL;
65 static int phase = 0, redoing = 0;
66 static flist_ndx_list batch_redo_list;
67 /* We're either updating the basis file or an identical copy: */
68 static int updating_basis_or_equiv;
70 #define TMPNAME_SUFFIX ".XXXXXX"
71 #define TMPNAME_SUFFIX_LEN ((int)sizeof TMPNAME_SUFFIX - 1)
72 #define MAX_UNIQUE_NUMBER 999999
73 #define MAX_UNIQUE_LOOP 100
75 /* get_tmpname() - create a tmp filename for a given filename
77 * If a tmpdir is defined, use that as the directory to put it in. Otherwise,
78 * the tmp filename is in the same directory as the given name. Note that
79 * there may be no directory at all in the given name!
81 * The tmp filename is basically the given filename with a dot prepended, and
82 * .XXXXXX appended (for mkstemp() to put its unique gunk in). We take care
83 * to not exceed either the MAXPATHLEN or NAME_MAX, especially the last, as
84 * the basename basically becomes 8 characters longer. In such a case, the
85 * original name is shortened sufficiently to make it all fit.
87 * If the make_unique arg is True, the XXXXXX string is replaced with a unique
88 * string that doesn't exist at the time of the check. This is intended to be
89 * used for creating hard links, symlinks, devices, and special files, since
90 * normal files should be handled by mkstemp() for safety.
92 * Of course, the only reason the file is based on the original name is to
93 * make it easier to figure out what purpose a temp file is serving when a
94 * transfer is in progress. */
95 int get_tmpname(char *fnametmp, const char *fname, BOOL make_unique)
97 int maxname, length = 0;
98 const char *f;
99 char *suf;
101 if (tmpdir) {
102 /* Note: this can't overflow, so the return value is safe */
103 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
104 fnametmp[length++] = '/';
107 if ((f = strrchr(fname, '/')) != NULL) {
108 ++f;
109 if (!tmpdir) {
110 length = f - fname;
111 /* copy up to and including the slash */
112 strlcpy(fnametmp, fname, length + 1);
114 } else
115 f = fname;
116 if (*f == '.') /* avoid an extra leading dot for OS X's sake */
117 f++;
118 fnametmp[length++] = '.';
120 /* The maxname value is bufsize, and includes space for the '\0'.
121 * NAME_MAX needs an extra -1 for the name's leading dot. */
122 maxname = MIN(MAXPATHLEN - length - TMPNAME_SUFFIX_LEN,
123 NAME_MAX - 1 - TMPNAME_SUFFIX_LEN);
125 if (maxname < 0) {
126 rprintf(FERROR_XFER, "temporary filename too long: %s\n", fname);
127 fnametmp[0] = '\0';
128 return 0;
131 if (maxname) {
132 int added = strlcpy(fnametmp + length, f, maxname);
133 if (added >= maxname)
134 added = maxname - 1;
135 suf = fnametmp + length + added;
137 /* Trim any dangling high-bit chars if the first-trimmed char (if any) is
138 * also a high-bit char, just in case we cut into a multi-byte sequence.
139 * We are guaranteed to stop because of the leading '.' we added. */
140 if ((int)f[added] & 0x80) {
141 while ((int)suf[-1] & 0x80)
142 suf--;
144 /* trim one trailing dot before our suffix's dot */
145 if (suf[-1] == '.')
146 suf--;
147 } else
148 suf = fnametmp + length - 1; /* overwrite the leading dot with suffix's dot */
150 if (make_unique) {
151 static unsigned counter_limit;
152 unsigned counter;
154 if (!counter_limit) {
155 counter_limit = (unsigned)getpid() + MAX_UNIQUE_LOOP;
156 if (counter_limit > MAX_UNIQUE_NUMBER || counter_limit < MAX_UNIQUE_LOOP)
157 counter_limit = MAX_UNIQUE_LOOP;
159 counter = counter_limit - MAX_UNIQUE_LOOP;
161 /* This doesn't have to be very good because we don't need
162 * to worry about someone trying to guess the values: all
163 * a conflict will do is cause a device, special file, hard
164 * link, or symlink to fail to be created. Also: avoid
165 * using mktemp() due to gcc's annoying warning. */
166 while (1) {
167 snprintf(suf, TMPNAME_SUFFIX_LEN+1, ".%d", counter);
168 if (access(fnametmp, 0) < 0)
169 break;
170 if (++counter >= counter_limit)
171 return 0;
173 } else
174 memcpy(suf, TMPNAME_SUFFIX, TMPNAME_SUFFIX_LEN+1);
176 return 1;
179 /* Opens a temporary file for writing.
180 * Success: Writes name into fnametmp, returns fd.
181 * Failure: Clobbers fnametmp, returns -1.
182 * Calling cleanup_set() is the caller's job. */
183 int open_tmpfile(char *fnametmp, const char *fname, struct file_struct *file)
185 int fd;
186 mode_t added_perms;
188 if (!get_tmpname(fnametmp, fname, False))
189 return -1;
191 if (am_root < 0) {
192 /* For --fake-super, the file must be useable by the copying
193 * user, just like it would be for root. */
194 added_perms = S_IRUSR|S_IWUSR;
195 } else {
196 /* For a normal copy, we need to be able to tweak things like xattrs. */
197 added_perms = S_IWUSR;
200 /* We initially set the perms without the setuid/setgid bits or group
201 * access to ensure that there is no race condition. They will be
202 * correctly updated after the right owner and group info is set.
203 * (Thanks to snabb@epipe.fi for pointing this out.) */
204 fd = do_mkstemp(fnametmp, (file->mode|added_perms) & INITACCESSPERMS);
206 #if 0
207 /* In most cases parent directories will already exist because their
208 * information should have been previously transferred, but that may
209 * not be the case with -R */
210 if (fd == -1 && relative_paths && errno == ENOENT
211 && make_path(fnametmp, MKP_SKIP_SLASH | MKP_DROP_NAME) == 0) {
212 /* Get back to name with XXXXXX in it. */
213 get_tmpname(fnametmp, fname, False);
214 fd = do_mkstemp(fnametmp, (file->mode|added_perms) & INITACCESSPERMS);
216 #endif
218 if (fd == -1) {
219 rsyserr(FERROR_XFER, errno, "mkstemp %s failed",
220 full_fname(fnametmp));
221 return -1;
224 return fd;
227 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
228 const char *fname, int fd, OFF_T total_size)
230 static char file_sum1[MAX_DIGEST_LEN];
231 struct map_struct *mapbuf;
232 struct sum_struct sum;
233 int32 len;
234 OFF_T offset = 0;
235 OFF_T offset2;
236 char *data;
237 int32 i;
238 char *map = NULL;
239 #ifdef SUPPORT_PREALLOCATION
240 #ifdef PREALLOCATE_NEEDS_TRUNCATE
241 OFF_T preallocated_len = 0;
242 #endif
244 if (preallocate_files && fd != -1 && total_size > 0 && (!inplace || total_size > size_r)) {
245 /* Try to preallocate enough space for file's eventual length. Can
246 * reduce fragmentation on filesystems like ext4, xfs, and NTFS. */
247 if (do_fallocate(fd, 0, total_size) == 0) {
248 #ifdef PREALLOCATE_NEEDS_TRUNCATE
249 preallocated_len = total_size;
250 #endif
251 } else
252 rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(fname));
254 #endif
256 read_sum_head(f_in, &sum);
258 if (fd_r >= 0 && size_r > 0) {
259 int32 read_size = MAX(sum.blength * 2, 16*1024);
260 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
261 if (DEBUG_GTE(DELTASUM, 2)) {
262 rprintf(FINFO, "recv mapped %s of size %s\n",
263 fname_r, big_num(size_r));
265 } else
266 mapbuf = NULL;
268 sum_init(checksum_seed);
270 if (append_mode > 0) {
271 OFF_T j;
272 sum.flength = (OFF_T)sum.count * sum.blength;
273 if (sum.remainder)
274 sum.flength -= sum.blength - sum.remainder;
275 if (append_mode == 2 && mapbuf) {
276 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
277 if (INFO_GTE(PROGRESS, 1))
278 show_progress(offset, total_size);
279 sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
280 CHUNK_SIZE);
281 offset = j;
283 if (offset < sum.flength) {
284 int32 len = (int32)(sum.flength - offset);
285 if (INFO_GTE(PROGRESS, 1))
286 show_progress(offset, total_size);
287 sum_update(map_ptr(mapbuf, offset, len), len);
290 offset = sum.flength;
291 if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) {
292 rsyserr(FERROR_XFER, errno, "lseek of %s returned %s, not %s",
293 full_fname(fname), big_num(j), big_num(offset));
294 exit_cleanup(RERR_FILEIO);
298 while ((i = recv_token(f_in, &data)) != 0) {
299 if (INFO_GTE(PROGRESS, 1))
300 show_progress(offset, total_size);
302 if (allowed_lull)
303 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH | MSK_ACTIVE_RECEIVER);
305 if (i > 0) {
306 if (DEBUG_GTE(DELTASUM, 3)) {
307 rprintf(FINFO,"data recv %d at %s\n",
308 i, big_num(offset));
311 stats.literal_data += i;
312 cleanup_got_literal = 1;
314 sum_update(data, i);
316 if (fd != -1 && write_file(fd,data,i) != i)
317 goto report_write_error;
318 offset += i;
319 continue;
322 i = -(i+1);
323 offset2 = i * (OFF_T)sum.blength;
324 len = sum.blength;
325 if (i == (int)sum.count-1 && sum.remainder != 0)
326 len = sum.remainder;
328 stats.matched_data += len;
330 if (DEBUG_GTE(DELTASUM, 3)) {
331 rprintf(FINFO,
332 "chunk[%d] of size %ld at %s offset=%s%s\n",
333 i, (long)len, big_num(offset2), big_num(offset),
334 updating_basis_or_equiv && offset == offset2 ? " (seek)" : "");
337 if (mapbuf) {
338 map = map_ptr(mapbuf,offset2,len);
340 see_token(map, len);
341 sum_update(map, len);
344 if (updating_basis_or_equiv) {
345 if (offset == offset2 && fd != -1) {
346 OFF_T pos;
347 if (flush_write_file(fd) < 0)
348 goto report_write_error;
349 offset += len;
350 if ((pos = do_lseek(fd, len, SEEK_CUR)) != offset) {
351 rsyserr(FERROR_XFER, errno,
352 "lseek of %s returned %s, not %s",
353 full_fname(fname),
354 big_num(pos), big_num(offset));
355 exit_cleanup(RERR_FILEIO);
357 continue;
360 if (fd != -1 && map && write_file(fd, map, len) != (int)len)
361 goto report_write_error;
362 offset += len;
365 if (flush_write_file(fd) < 0)
366 goto report_write_error;
368 #ifdef HAVE_FTRUNCATE
369 /* inplace: New data could be shorter than old data.
370 * preallocate_files: total_size could have been an overestimate.
371 * Cut off any extra preallocated zeros from dest file. */
372 if ((inplace
373 #ifdef PREALLOCATE_NEEDS_TRUNCATE
374 || preallocated_len > offset
375 #endif
376 ) && fd != -1 && do_ftruncate(fd, offset) < 0) {
377 rsyserr(FERROR_XFER, errno, "ftruncate failed on %s",
378 full_fname(fname));
380 #endif
382 if (INFO_GTE(PROGRESS, 1))
383 end_progress(total_size);
385 if (fd != -1 && offset > 0 && sparse_end(fd, offset) != 0) {
386 report_write_error:
387 rsyserr(FERROR_XFER, errno, "write failed on %s",
388 full_fname(fname));
389 exit_cleanup(RERR_FILEIO);
392 if (sum_end(file_sum1) != checksum_len)
393 overflow_exit("checksum_len"); /* Impossible... */
395 if (mapbuf)
396 unmap_file(mapbuf);
398 read_buf(f_in, sender_file_sum, checksum_len);
399 if (DEBUG_GTE(DELTASUM, 2))
400 rprintf(FINFO,"got file_sum\n");
401 if (fd != -1 && memcmp(file_sum1, sender_file_sum, checksum_len) != 0)
402 return 0;
403 return 1;
407 static void discard_receive_data(int f_in, OFF_T length)
409 receive_data(f_in, NULL, -1, 0, NULL, -1, length);
412 static void handle_delayed_updates(char *local_name)
414 char *fname, *partialptr;
415 int ndx;
417 for (ndx = -1; (ndx = bitbag_next_bit(delayed_bits, ndx)) >= 0; ) {
418 struct file_struct *file = cur_flist->files[ndx];
419 fname = local_name ? local_name : f_name(file, NULL);
420 if ((partialptr = partial_dir_fname(fname)) != NULL) {
421 if (make_backups > 0 && !make_backup(fname, False))
422 continue;
423 if (DEBUG_GTE(RECV, 1)) {
424 rprintf(FINFO, "renaming %s to %s\n",
425 partialptr, fname);
427 /* We don't use robust_rename() here because the
428 * partial-dir must be on the same drive. */
429 if (do_rename(partialptr, fname) < 0) {
430 rsyserr(FERROR_XFER, errno,
431 "rename failed for %s (from %s)",
432 full_fname(fname), partialptr);
433 } else {
434 if (remove_source_files
435 || (preserve_hard_links && F_IS_HLINKED(file)))
436 send_msg_int(MSG_SUCCESS, ndx);
437 handle_partial_dir(partialptr, PDIR_DELETE);
443 static void no_batched_update(int ndx, BOOL is_redo)
445 struct file_list *flist = flist_for_ndx(ndx, "no_batched_update");
446 struct file_struct *file = flist->files[ndx - flist->ndx_start];
448 rprintf(FERROR_XFER, "(No batched update for%s \"%s\")\n",
449 is_redo ? " resend of" : "", f_name(file, NULL));
451 if (inc_recurse && !dry_run)
452 send_msg_int(MSG_NO_SEND, ndx);
455 static int we_want_redo(int desired_ndx)
457 static int redo_ndx = -1;
459 while (redo_ndx < desired_ndx) {
460 if (redo_ndx >= 0)
461 no_batched_update(redo_ndx, True);
462 if ((redo_ndx = flist_ndx_pop(&batch_redo_list)) < 0)
463 return 0;
466 if (redo_ndx == desired_ndx) {
467 redo_ndx = -1;
468 return 1;
471 return 0;
474 static int gen_wants_ndx(int desired_ndx, int flist_num)
476 static int next_ndx = -1;
477 static int done_cnt = 0;
478 static BOOL got_eof = False;
480 if (got_eof)
481 return 0;
483 /* TODO: integrate gen-reading I/O into perform_io() so this is not needed? */
484 io_flush(FULL_FLUSH);
486 while (next_ndx < desired_ndx) {
487 if (inc_recurse && flist_num <= done_cnt)
488 return 0;
489 if (next_ndx >= 0)
490 no_batched_update(next_ndx, False);
491 if ((next_ndx = read_int(batch_gen_fd)) < 0) {
492 if (inc_recurse) {
493 done_cnt++;
494 continue;
496 got_eof = True;
497 return 0;
501 if (next_ndx == desired_ndx) {
502 next_ndx = -1;
503 return 1;
506 return 0;
510 * main routine for receiver process.
512 * Receiver process runs on the same host as the generator process. */
513 int recv_files(int f_in, int f_out, char *local_name)
515 int fd1,fd2;
516 STRUCT_STAT st;
517 int iflags, xlen;
518 char *fname, fbuf[MAXPATHLEN];
519 char xname[MAXPATHLEN];
520 char fnametmp[MAXPATHLEN];
521 char *fnamecmp, *partialptr;
522 char fnamecmpbuf[MAXPATHLEN];
523 uchar fnamecmp_type;
524 struct file_struct *file;
525 int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
526 enum logcode log_code = log_before_transfer ? FLOG : FINFO;
527 int max_phase = protocol_version >= 29 ? 2 : 1;
528 int dflt_perms = (ACCESSPERMS & ~orig_umask);
529 #ifdef SUPPORT_ACLS
530 const char *parent_dirname = "";
531 #endif
532 int ndx, recv_ok;
534 if (DEBUG_GTE(RECV, 1))
535 rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used);
537 if (delay_updates)
538 delayed_bits = bitbag_create(cur_flist->used + 1);
540 while (1) {
541 cleanup_disable();
543 /* This call also sets cur_flist. */
544 ndx = read_ndx_and_attrs(f_in, f_out, &iflags, &fnamecmp_type,
545 xname, &xlen);
546 if (ndx == NDX_DONE) {
547 if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) {
548 set_current_file_index(NULL, 0);
549 end_progress(0);
551 if (inc_recurse && first_flist) {
552 if (read_batch) {
553 ndx = first_flist->used + first_flist->ndx_start;
554 gen_wants_ndx(ndx, first_flist->flist_num);
556 flist_free(first_flist);
557 if (first_flist)
558 continue;
559 } else if (read_batch && first_flist) {
560 ndx = first_flist->used;
561 gen_wants_ndx(ndx, first_flist->flist_num);
563 if (++phase > max_phase)
564 break;
565 if (DEBUG_GTE(RECV, 1))
566 rprintf(FINFO, "recv_files phase=%d\n", phase);
567 if (phase == 2 && delay_updates)
568 handle_delayed_updates(local_name);
569 write_int(f_out, NDX_DONE);
570 continue;
573 if (ndx - cur_flist->ndx_start >= 0)
574 file = cur_flist->files[ndx - cur_flist->ndx_start];
575 else
576 file = dir_flist->files[cur_flist->parent_ndx];
577 fname = local_name ? local_name : f_name(file, fbuf);
579 if (DEBUG_GTE(RECV, 1))
580 rprintf(FINFO, "recv_files(%s)\n", fname);
582 #ifdef SUPPORT_XATTRS
583 if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
584 && (protocol_version < 31 || !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE)))
585 recv_xattr_request(file, f_in);
586 #endif
588 if (!(iflags & ITEM_TRANSFER)) {
589 maybe_log_item(file, iflags, itemizing, xname);
590 #ifdef SUPPORT_XATTRS
591 if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && do_xfers
592 && !BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))
593 set_file_attrs(fname, file, NULL, fname, 0);
594 #endif
595 if (iflags & ITEM_IS_NEW) {
596 stats.created_files++;
597 if (S_ISREG(file->mode)) {
598 /* Nothing further to count. */
599 } else if (S_ISDIR(file->mode))
600 stats.created_dirs++;
601 #ifdef SUPPORT_LINKS
602 else if (S_ISLNK(file->mode))
603 stats.created_symlinks++;
604 #endif
605 else if (IS_DEVICE(file->mode))
606 stats.created_devices++;
607 else
608 stats.created_specials++;
610 continue;
612 if (phase == 2) {
613 rprintf(FERROR,
614 "got transfer request in phase 2 [%s]\n",
615 who_am_i());
616 exit_cleanup(RERR_PROTOCOL);
619 if (file->flags & FLAG_FILE_SENT) {
620 if (csum_length == SHORT_SUM_LENGTH) {
621 if (keep_partial && !partial_dir)
622 make_backups = -make_backups; /* prevents double backup */
623 if (append_mode)
624 sparse_files = -sparse_files;
625 append_mode = -append_mode;
626 csum_length = SUM_LENGTH;
627 redoing = 1;
629 } else {
630 if (csum_length != SHORT_SUM_LENGTH) {
631 if (keep_partial && !partial_dir)
632 make_backups = -make_backups;
633 if (append_mode)
634 sparse_files = -sparse_files;
635 append_mode = -append_mode;
636 csum_length = SHORT_SUM_LENGTH;
637 redoing = 0;
639 if (iflags & ITEM_IS_NEW)
640 stats.created_files++;
643 if (!am_server && INFO_GTE(PROGRESS, 1))
644 set_current_file_index(file, ndx);
645 stats.xferred_files++;
646 stats.total_transferred_size += F_LENGTH(file);
648 cleanup_got_literal = 0;
650 if (daemon_filter_list.head
651 && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) {
652 rprintf(FERROR, "attempt to hack rsync failed.\n");
653 exit_cleanup(RERR_PROTOCOL);
656 if (read_batch) {
657 int wanted = redoing
658 ? we_want_redo(ndx)
659 : gen_wants_ndx(ndx, cur_flist->flist_num);
660 if (!wanted) {
661 rprintf(FINFO,
662 "(Skipping batched update for%s \"%s\")\n",
663 redoing ? " resend of" : "",
664 fname);
665 discard_receive_data(f_in, F_LENGTH(file));
666 file->flags |= FLAG_FILE_SENT;
667 continue;
671 if (!log_before_transfer)
672 remember_initial_stats();
674 if (!do_xfers) { /* log the transfer */
675 log_item(FCLIENT, file, iflags, NULL);
676 if (read_batch)
677 discard_receive_data(f_in, F_LENGTH(file));
678 continue;
680 if (write_batch < 0) {
681 log_item(FCLIENT, file, iflags, NULL);
682 if (!am_server)
683 discard_receive_data(f_in, F_LENGTH(file));
684 if (inc_recurse)
685 send_msg_int(MSG_SUCCESS, ndx);
686 continue;
689 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
691 if (protocol_version >= 29) {
692 switch (fnamecmp_type) {
693 case FNAMECMP_FNAME:
694 fnamecmp = fname;
695 break;
696 case FNAMECMP_PARTIAL_DIR:
697 fnamecmp = partialptr;
698 break;
699 case FNAMECMP_BACKUP:
700 fnamecmp = get_backup_name(fname);
701 break;
702 case FNAMECMP_FUZZY:
703 if (file->dirname) {
704 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, file->dirname, xname);
705 fnamecmp = fnamecmpbuf;
706 } else
707 fnamecmp = xname;
708 break;
709 default:
710 if (fnamecmp_type > FNAMECMP_FUZZY && fnamecmp_type-FNAMECMP_FUZZY <= basis_dir_cnt) {
711 fnamecmp_type -= FNAMECMP_FUZZY + 1;
712 if (file->dirname) {
713 stringjoin(fnamecmpbuf, sizeof fnamecmpbuf,
714 basis_dir[fnamecmp_type], "/", file->dirname, "/", xname, NULL);
715 } else
716 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], xname);
717 } else if (fnamecmp_type >= basis_dir_cnt) {
718 rprintf(FERROR,
719 "invalid basis_dir index: %d.\n",
720 fnamecmp_type);
721 exit_cleanup(RERR_PROTOCOL);
722 } else
723 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf, basis_dir[fnamecmp_type], fname);
724 fnamecmp = fnamecmpbuf;
725 break;
727 if (!fnamecmp || (daemon_filter_list.head
728 && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) {
729 fnamecmp = fname;
730 fnamecmp_type = FNAMECMP_FNAME;
732 } else {
733 /* Reminder: --inplace && --partial-dir are never
734 * enabled at the same time. */
735 if (inplace && make_backups > 0) {
736 if (!(fnamecmp = get_backup_name(fname)))
737 fnamecmp = fname;
738 else
739 fnamecmp_type = FNAMECMP_BACKUP;
740 } else if (partial_dir && partialptr)
741 fnamecmp = partialptr;
742 else
743 fnamecmp = fname;
746 /* open the file */
747 fd1 = do_open(fnamecmp, O_RDONLY, 0);
749 if (fd1 == -1 && protocol_version < 29) {
750 if (fnamecmp != fname) {
751 fnamecmp = fname;
752 fd1 = do_open(fnamecmp, O_RDONLY, 0);
755 if (fd1 == -1 && basis_dir[0]) {
756 /* pre-29 allowed only one alternate basis */
757 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
758 basis_dir[0], fname);
759 fnamecmp = fnamecmpbuf;
760 fd1 = do_open(fnamecmp, O_RDONLY, 0);
764 updating_basis_or_equiv = inplace
765 && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP);
767 if (fd1 == -1) {
768 st.st_mode = 0;
769 st.st_size = 0;
770 } else if (do_fstat(fd1,&st) != 0) {
771 rsyserr(FERROR_XFER, errno, "fstat %s failed",
772 full_fname(fnamecmp));
773 discard_receive_data(f_in, F_LENGTH(file));
774 close(fd1);
775 if (inc_recurse)
776 send_msg_int(MSG_NO_SEND, ndx);
777 continue;
780 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
781 /* this special handling for directories
782 * wouldn't be necessary if robust_rename()
783 * and the underlying robust_unlink could cope
784 * with directories
786 rprintf(FERROR_XFER, "recv_files: %s is a directory\n",
787 full_fname(fnamecmp));
788 discard_receive_data(f_in, F_LENGTH(file));
789 close(fd1);
790 if (inc_recurse)
791 send_msg_int(MSG_NO_SEND, ndx);
792 continue;
795 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
796 close(fd1);
797 fd1 = -1;
800 /* If we're not preserving permissions, change the file-list's
801 * mode based on the local permissions and some heuristics. */
802 if (!preserve_perms) {
803 int exists = fd1 != -1;
804 #ifdef SUPPORT_ACLS
805 const char *dn = file->dirname ? file->dirname : ".";
806 if (parent_dirname != dn
807 && strcmp(parent_dirname, dn) != 0) {
808 dflt_perms = default_perms_for_dir(dn);
809 parent_dirname = dn;
811 #endif
812 file->mode = dest_mode(file->mode, st.st_mode,
813 dflt_perms, exists);
816 /* We now check to see if we are writing the file "inplace" */
817 if (inplace) {
818 fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
819 if (fd2 == -1) {
820 rsyserr(FERROR_XFER, errno, "open %s failed",
821 full_fname(fname));
822 } else if (updating_basis_or_equiv)
823 cleanup_set(NULL, NULL, file, fd1, fd2);
824 } else {
825 fd2 = open_tmpfile(fnametmp, fname, file);
826 if (fd2 != -1)
827 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
830 if (fd2 == -1) {
831 discard_receive_data(f_in, F_LENGTH(file));
832 if (fd1 != -1)
833 close(fd1);
834 if (inc_recurse)
835 send_msg_int(MSG_NO_SEND, ndx);
836 continue;
839 /* log the transfer */
840 if (log_before_transfer)
841 log_item(FCLIENT, file, iflags, NULL);
842 else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))
843 rprintf(FINFO, "%s\n", fname);
845 /* recv file data */
846 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
847 fname, fd2, F_LENGTH(file));
849 log_item(log_code, file, iflags, NULL);
851 if (fd1 != -1)
852 close(fd1);
853 if (close(fd2) < 0) {
854 rsyserr(FERROR, errno, "close failed on %s",
855 full_fname(fnametmp));
856 exit_cleanup(RERR_FILEIO);
859 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
860 if (partialptr == fname)
861 partialptr = NULL;
862 if (!finish_transfer(fname, fnametmp, fnamecmp,
863 partialptr, file, recv_ok, 1))
864 recv_ok = -1;
865 else if (fnamecmp == partialptr) {
866 do_unlink(partialptr);
867 handle_partial_dir(partialptr, PDIR_DELETE);
869 } else if (keep_partial && partialptr) {
870 if (!handle_partial_dir(partialptr, PDIR_CREATE)) {
871 rprintf(FERROR,
872 "Unable to create partial-dir for %s -- discarding %s.\n",
873 local_name ? local_name : f_name(file, NULL),
874 recv_ok ? "completed file" : "partial file");
875 do_unlink(fnametmp);
876 recv_ok = -1;
877 } else if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,
878 file, recv_ok, !partial_dir))
879 recv_ok = -1;
880 else if (delay_updates && recv_ok) {
881 bitbag_set_bit(delayed_bits, ndx);
882 recv_ok = 2;
883 } else
884 partialptr = NULL;
885 } else
886 do_unlink(fnametmp);
888 cleanup_disable();
890 if (read_batch)
891 file->flags |= FLAG_FILE_SENT;
893 switch (recv_ok) {
894 case 2:
895 break;
896 case 1:
897 if (remove_source_files || inc_recurse
898 || (preserve_hard_links && F_IS_HLINKED(file)))
899 send_msg_int(MSG_SUCCESS, ndx);
900 break;
901 case 0: {
902 enum logcode msgtype = redoing ? FERROR_XFER : FWARNING;
903 if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) {
904 char *errstr, *redostr, *keptstr;
905 if (!(keep_partial && partialptr) && !inplace)
906 keptstr = "discarded";
907 else if (partial_dir)
908 keptstr = "put into partial-dir";
909 else
910 keptstr = "retained";
911 if (msgtype == FERROR_XFER) {
912 errstr = "ERROR";
913 redostr = "";
914 } else {
915 errstr = "WARNING";
916 redostr = read_batch ? " (may try again)"
917 : " (will try again)";
919 rprintf(msgtype,
920 "%s: %s failed verification -- update %s%s.\n",
921 errstr, local_name ? f_name(file, NULL) : fname,
922 keptstr, redostr);
924 if (!redoing) {
925 if (read_batch)
926 flist_ndx_push(&batch_redo_list, ndx);
927 send_msg_int(MSG_REDO, ndx);
928 file->flags |= FLAG_FILE_SENT;
929 } else if (inc_recurse)
930 send_msg_int(MSG_NO_SEND, ndx);
931 break;
933 case -1:
934 if (inc_recurse)
935 send_msg_int(MSG_NO_SEND, ndx);
936 break;
939 if (make_backups < 0)
940 make_backups = -make_backups;
942 if (phase == 2 && delay_updates) /* for protocol_version < 29 */
943 handle_delayed_updates(local_name);
945 if (DEBUG_GTE(RECV, 1))
946 rprintf(FINFO,"recv_files finished\n");
948 return 0;