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