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