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