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