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