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