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