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