The patches for 3.1.1pre1.
[rsync-patches.git] / detect-renamed.diff
1 This patch adds the --detect-renamed option which makes rsync notice files
2 that either (1) match in size & modify-time (plus the basename, if possible)
3 or (2) match in size & checksum (when --checksum was also specified) and use
4 each match as an alternate basis file to speed up the transfer.
5
6 The algorithm attempts to scan the receiving-side's files in an efficient
7 manner.  If --delete[-before] is enabled, we'll take advantage of the
8 pre-transfer delete pass to prepare any alternate-basis-file matches we
9 might find.  If --delete-before is not enabled, rsync does the rename scan
10 during the regular file-sending scan (scanning each directory right before
11 the generator starts updating files from that dir).  In this latter mode,
12 rsync might delay the updating of a file (if no alternate-basis match was
13 yet found) until the full scan of the receiving side is complete, at which
14 point any delayed files are processed.
15
16 I chose to hard-link the alternate-basis files into a ".~tmp~" subdir that
17 takes advantage of rsync's pre-existing partial-dir logic.  This uses less
18 memory than trying to keep track of the matches internally, and also allows
19 any deletions or file-updates to occur normally without interfering with
20 these alternate-basis discoveries.
21
22 To use this patch, run these commands for a successful build:
23
24     patch -p1 <patches/detect-renamed.diff
25     ./configure                                 (optional if already run)
26     make
27
28 TODO:
29
30   The routine that makes missing directories for files that get renamed
31   down into a new sub-hierarchy doesn't properly handle the case where some
32   path elements might exist but not be a dir yet.  We need to either change
33   our stash-ahead algorithm (to not require unknown path elements) or we
34   need to create a better path-making routine.
35
36   We need to never return a match from fattr_find() that has a basis
37   file.  This will ensure that we don't try to give a renamed file to
38   a file that can't use it, while missing out on giving it to a file
39   that could use it.
40
41 based-on: 8946cfc6f8018e30740ee1db4cc2e2008e4f7e7e
42 diff --git a/compat.c b/compat.c
43 --- a/compat.c
44 +++ b/compat.c
45 @@ -43,6 +43,7 @@ extern int checksum_seed;
46  extern int basis_dir_cnt;
47  extern int prune_empty_dirs;
48  extern int protocol_version;
49 +extern int detect_renamed;
50  extern int protect_args;
51  extern int preserve_uid;
52  extern int preserve_gid;
53 @@ -123,6 +124,7 @@ void set_allow_inc_recurse(void)
54                 allow_inc_recurse = 0;
55         else if (!am_sender
56          && (delete_before || delete_after
57 +         || detect_renamed
58           || delay_updates || prune_empty_dirs))
59                 allow_inc_recurse = 0;
60         else if (am_server && !local_server
61 diff --git a/delete.c b/delete.c
62 --- a/delete.c
63 +++ b/delete.c
64 @@ -25,6 +25,7 @@
65  extern int am_root;
66  extern int make_backups;
67  extern int max_delete;
68 +extern int detect_renamed;
69  extern char *backup_dir;
70  extern char *backup_suffix;
71  extern int backup_suffix_len;
72 @@ -44,6 +45,8 @@ static inline int is_backup_file(char *fn)
73   * its contents, otherwise just checks for content.  Returns DR_SUCCESS or
74   * DR_NOT_EMPTY.  Note that fname must point to a MAXPATHLEN buffer!  (The
75   * buffer is used for recursion, but returned unchanged.)
76 + *
77 + * Note: --detect-rename may use this routine with DEL_NO_DELETIONS set!
78   */
79  static enum delret delete_dir_contents(char *fname, uint16 flags)
80  {
81 @@ -63,7 +66,9 @@ static enum delret delete_dir_contents(char *fname, uint16 flags)
82         save_filters = push_local_filters(fname, dlen);
83  
84         non_perishable_cnt = 0;
85 +       file_extra_cnt += SUM_EXTRA_CNT;
86         dirlist = get_dirlist(fname, dlen, 0);
87 +       file_extra_cnt -= SUM_EXTRA_CNT;
88         ret = non_perishable_cnt ? DR_NOT_EMPTY : DR_SUCCESS;
89  
90         if (!dirlist->used)
91 @@ -103,7 +108,8 @@ static enum delret delete_dir_contents(char *fname, uint16 flags)
92                 if (S_ISDIR(fp->mode)) {
93                         if (delete_dir_contents(fname, flags | DEL_RECURSE) != DR_SUCCESS)
94                                 ret = DR_NOT_EMPTY;
95 -               }
96 +               } else if (detect_renamed && S_ISREG(fp->mode))
97 +                       look_for_rename(fp, fname);
98                 if (delete_item(fname, fp->mode, flags) != DR_SUCCESS)
99                         ret = DR_NOT_EMPTY;
100         }
101 @@ -126,6 +132,8 @@ static enum delret delete_dir_contents(char *fname, uint16 flags)
102   *
103   * Note that fbuf must point to a MAXPATHLEN buffer if the mode indicates it's
104   * a directory! (The buffer is used for recursion, but returned unchanged.)
105 + *
106 + * Also note: --detect-rename may use this routine with DEL_NO_DELETIONS set!
107   */
108  enum delret delete_item(char *fbuf, uint16 mode, uint16 flags)
109  {
110 diff --git a/flist.c b/flist.c
111 --- a/flist.c
112 +++ b/flist.c
113 @@ -60,6 +60,7 @@ extern int non_perishable_cnt;
114  extern int prune_empty_dirs;
115  extern int copy_links;
116  extern int copy_unsafe_links;
117 +extern int detect_renamed;
118  extern int protocol_version;
119  extern int sanitize_paths;
120  extern int munge_symlinks;
121 @@ -125,6 +126,8 @@ static int64 tmp_dev = -1, tmp_ino;
122  #endif
123  static char tmp_sum[MAX_DIGEST_LEN];
124  
125 +struct file_list the_fattr_list;
126 +
127  static char empty_sum[MAX_DIGEST_LEN];
128  static int flist_count_offset; /* for --delete --progress */
129  
130 @@ -292,6 +295,45 @@ static int is_excluded(const char *fname, int is_dir, int filter_level)
131         return 0;
132  }
133  
134 +static int fattr_compare(struct file_struct **file1, struct file_struct **file2)
135 +{
136 +       struct file_struct *f1 = *file1;
137 +       struct file_struct *f2 = *file2;
138 +       int64 len1 = F_LENGTH(f1), len2 = F_LENGTH(f2);
139 +       int diff;
140 +
141 +       if (!f1->basename || !S_ISREG(f1->mode) || !len1) {
142 +               if (!f2->basename || !S_ISREG(f2->mode) || !len2)
143 +                       return 0;
144 +               return 1;
145 +       }
146 +       if (!f2->basename || !S_ISREG(f2->mode) || !len2)
147 +               return -1;
148 +
149 +       /* Don't use diff for values that are longer than an int. */
150 +       if (len1 != len2)
151 +               return len1 < len2 ? -1 : 1;
152 +
153 +       if (always_checksum) {
154 +               diff = u_memcmp(F_SUM(f1), F_SUM(f2), checksum_len);
155 +               if (diff)
156 +                       return diff;
157 +       } else if (f1->modtime != f2->modtime)
158 +               return f1->modtime < f2->modtime ? -1 : 1;
159 +
160 +       diff = u_strcmp(f1->basename, f2->basename);
161 +       if (diff)
162 +               return diff;
163 +
164 +       if (f1->dirname == f2->dirname)
165 +               return 0;
166 +       if (!f1->dirname)
167 +               return -1;
168 +       if (!f2->dirname)
169 +               return 1;
170 +       return u_strcmp(f1->dirname, f2->dirname);
171 +}
172 +
173  static void send_directory(int f, struct file_list *flist,
174                            char *fbuf, int len, int flags);
175  
176 @@ -2555,6 +2597,25 @@ struct file_list *recv_file_list(int f)
177  
178         flist_sort_and_clean(flist, relative_paths);
179  
180 +       if (detect_renamed) {
181 +               int j = flist->used;
182 +               the_fattr_list.used = j;
183 +               the_fattr_list.files = new_array(struct file_struct *, j);
184 +               if (!the_fattr_list.files)
185 +                       out_of_memory("recv_file_list");
186 +               memcpy(the_fattr_list.files, flist->files,
187 +                      j * sizeof (struct file_struct *));
188 +               qsort(the_fattr_list.files, j,
189 +                     sizeof the_fattr_list.files[0], (int (*)())fattr_compare);
190 +               the_fattr_list.low = 0;
191 +               while (j-- > 0) {
192 +                       struct file_struct *fp = the_fattr_list.files[j];
193 +                       if (fp->basename && S_ISREG(fp->mode) && F_LENGTH(fp))
194 +                               break;
195 +               }
196 +               the_fattr_list.high = j;
197 +       }
198 +
199         if (protocol_version < 30) {
200                 /* Recv the io_error flag */
201                 int err = read_int(f);
202 diff --git a/generator.c b/generator.c
203 --- a/generator.c
204 +++ b/generator.c
205 @@ -78,6 +78,7 @@ extern char *partial_dir;
206  extern int compare_dest;
207  extern int copy_dest;
208  extern int link_dest;
209 +extern int detect_renamed;
210  extern int whole_file;
211  extern int list_only;
212  extern int read_batch;
213 @@ -96,10 +97,12 @@ extern char *tmpdir;
214  extern char *basis_dir[MAX_BASIS_DIRS+1];
215  extern struct file_list *cur_flist, *first_flist, *dir_flist;
216  extern filter_rule_list filter_list, daemon_filter_list;
217 +extern struct file_list the_fattr_list;
218  
219  int maybe_ATTRS_REPORT = 0;
220  
221  static dev_t dev_zero;
222 +static int unexplored_dirs = 1;
223  static int deldelay_size = 0, deldelay_cnt = 0;
224  static char *deldelay_buf = NULL;
225  static int deldelay_fd = -1;
226 @@ -179,6 +182,8 @@ static int remember_delete(struct file_struct *file, const char *fname, int flag
227                 if (!flush_delete_delay())
228                         return 0;
229         }
230 +       if (flags & DEL_NO_DELETIONS)
231 +               return DR_SUCCESS;
232  
233         return 1;
234  }
235 @@ -270,13 +275,18 @@ static void do_delayed_deletions(char *delbuf)
236   * all the --delete-WHEN options.  Note that the fbuf pointer must point to a
237   * MAXPATHLEN buffer with the name of the directory in it (the functions we
238   * call will append names onto the end, but the old dir value will be restored
239 - * on exit). */
240 -static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev)
241 + * on exit).
242 + *
243 + * Note:  --detect-rename may use this routine with DEL_NO_DELETIONS set!
244 + */
245 +static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev,
246 +                         int del_flags)
247  {
248         static int already_warned = 0;
249         struct file_list *dirlist;
250 -       char delbuf[MAXPATHLEN];
251 -       int dlen, i;
252 +       char *p, delbuf[MAXPATHLEN];
253 +       unsigned remainder;
254 +       int dlen, i, restore_dot = 0;
255  
256         if (!fbuf) {
257                 change_local_filter_dir(NULL, 0, 0);
258 @@ -290,17 +300,22 @@ static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev)
259                 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
260  
261         if (io_error & IOERR_GENERAL && !ignore_errors) {
262 -               if (already_warned)
263 +               if (!already_warned) {
264 +                       rprintf(FINFO,
265 +                           "IO error encountered -- skipping file deletion\n");
266 +                       already_warned = 1;
267 +               }
268 +               if (!detect_renamed)
269                         return;
270 -               rprintf(FINFO,
271 -                       "IO error encountered -- skipping file deletion\n");
272 -               already_warned = 1;
273 -               return;
274 +               del_flags |= DEL_NO_DELETIONS;
275         }
276  
277         dlen = strlen(fbuf);
278         change_local_filter_dir(fbuf, dlen, F_DEPTH(file));
279  
280 +       if (detect_renamed)
281 +               unexplored_dirs--;
282 +
283         if (one_file_system) {
284                 if (file->flags & FLAG_TOP_DIR)
285                         filesystem_dev = *fs_dev;
286 @@ -310,6 +325,14 @@ static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev)
287  
288         dirlist = get_dirlist(fbuf, dlen, 0);
289  
290 +       p = fbuf + dlen;
291 +       if (dlen == 1 && *fbuf == '.') {
292 +               restore_dot = 1;
293 +               p = fbuf;
294 +       } else if (dlen != 1 || *fbuf != '/')
295 +               *p++ = '/';
296 +       remainder = MAXPATHLEN - (p - fbuf);
297 +
298         /* If an item in dirlist is not found in flist, delete it
299          * from the filesystem. */
300         for (i = dirlist->used; i--; ) {
301 @@ -322,6 +345,10 @@ static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev)
302                                         f_name(fp, NULL));
303                         continue;
304                 }
305 +               if (detect_renamed && S_ISREG(fp->mode)) {
306 +                       strlcpy(p, fp->basename, remainder);
307 +                       look_for_rename(fp, fbuf);
308 +               }
309                 /* Here we want to match regardless of file type.  Replacement
310                  * of a file with one of another type is handled separately by
311                  * a delete_item call with a DEL_MAKE_ROOM flag. */
312 @@ -330,14 +357,19 @@ static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev)
313                         if (!(fp->mode & S_IWUSR) && !am_root && fp->flags & FLAG_OWNED_BY_US)
314                                 flags |= DEL_NO_UID_WRITE;
315                         f_name(fp, delbuf);
316 -                       if (delete_during == 2) {
317 -                               if (!remember_delete(fp, delbuf, flags))
318 +                       if (delete_during == 2 && !(del_flags & DEL_NO_DELETIONS)) {
319 +                               if (!remember_delete(fp, delbuf, del_flags | flags))
320                                         break;
321                         } else
322 -                               delete_item(delbuf, fp->mode, flags);
323 -               }
324 +                               delete_item(delbuf, fp->mode, del_flags | flags);
325 +               } else if (detect_renamed && S_ISDIR(fp->mode))
326 +                       unexplored_dirs++;
327         }
328  
329 +       if (restore_dot)
330 +               fbuf[0] = '.';
331 +       fbuf[dlen] = '\0';
332 +
333         flist_free(dirlist);
334  }
335  
336 @@ -370,14 +402,122 @@ static void do_delete_pass(void)
337                  || !S_ISDIR(st.st_mode))
338                         continue;
339  
340 -               delete_in_dir(fbuf, file, &st.st_dev);
341 +               delete_in_dir(fbuf, file, &st.st_dev, 0);
342         }
343 -       delete_in_dir(NULL, NULL, &dev_zero);
344 +       delete_in_dir(NULL, NULL, &dev_zero, 0);
345  
346         if (INFO_GTE(FLIST, 2) && !am_server)
347                 rprintf(FINFO, "                    \r");
348  }
349  
350 +/* Search for a regular file that matches either (1) the size & modified
351 + * time (plus the basename, if possible) or (2) the size & checksum.  If
352 + * we find an exact match down to the dirname, return -1 because we found
353 + * an up-to-date file in the transfer, not a renamed file. */
354 +static int fattr_find(struct file_struct *f, char *fname)
355 +{
356 +       int low = the_fattr_list.low, high = the_fattr_list.high;
357 +       int mid, ok_match = -1, good_match = -1;
358 +       struct file_struct *fmid;
359 +       int diff;
360 +
361 +       while (low <= high) {
362 +               mid = (low + high) / 2;
363 +               fmid = the_fattr_list.files[mid];
364 +               if (F_LENGTH(fmid) != F_LENGTH(f)) {
365 +                       if (F_LENGTH(fmid) < F_LENGTH(f))
366 +                               low = mid + 1;
367 +                       else
368 +                               high = mid - 1;
369 +                       continue;
370 +               }
371 +               if (always_checksum) {
372 +                       /* We use the FLAG_FILE_SENT flag to indicate when we
373 +                        * have computed the checksum for an entry. */
374 +                       if (!(f->flags & FLAG_FILE_SENT)) {
375 +                               if (fmid->modtime == f->modtime
376 +                                && f_name_cmp(fmid, f) == 0)
377 +                                       return -1; /* assume we can't help */
378 +                               file_checksum(fname, F_SUM(f), F_LENGTH(f));
379 +                               f->flags |= FLAG_FILE_SENT;
380 +                       }
381 +                       diff = u_memcmp(F_SUM(fmid), F_SUM(f), checksum_len);
382 +                       if (diff) {
383 +                               if (diff < 0)
384 +                                       low = mid + 1;
385 +                               else
386 +                                       high = mid - 1;
387 +                               continue;
388 +                       }
389 +               } else {
390 +                       if (fmid->modtime != f->modtime) {
391 +                               if (fmid->modtime < f->modtime)
392 +                                       low = mid + 1;
393 +                               else
394 +                                       high = mid - 1;
395 +                               continue;
396 +                       }
397 +               }
398 +               ok_match = mid;
399 +               diff = u_strcmp(fmid->basename, f->basename);
400 +               if (diff == 0) {
401 +                       good_match = mid;
402 +                       if (fmid->dirname == f->dirname)
403 +                               return -1; /* file is up-to-date */
404 +                       if (!fmid->dirname) {
405 +                               low = mid + 1;
406 +                               continue;
407 +                       }
408 +                       if (!f->dirname) {
409 +                               high = mid - 1;
410 +                               continue;
411 +                       }
412 +                       diff = u_strcmp(fmid->dirname, f->dirname);
413 +                       if (diff == 0)
414 +                               return -1; /* file is up-to-date */
415 +               }
416 +               if (diff < 0)
417 +                       low = mid + 1;
418 +               else
419 +                       high = mid - 1;
420 +       }
421 +
422 +       return good_match >= 0 ? good_match : ok_match;
423 +}
424 +
425 +void look_for_rename(struct file_struct *file, char *fname)
426 +{
427 +       struct file_struct *fp;
428 +       char *partialptr, *fn;
429 +       STRUCT_STAT st;
430 +       int ndx;
431 +
432 +       if (!partial_dir || (ndx = fattr_find(file, fname)) < 0)
433 +               return;
434 +
435 +       fp = the_fattr_list.files[ndx];
436 +       fn = f_name(fp, NULL);
437 +       /* We don't provide an alternate-basis file if there is a basis file. */
438 +       if (link_stat(fn, &st, 0) == 0)
439 +               return;
440 +
441 +       if (!dry_run) {
442 +               if ((partialptr = partial_dir_fname(fn)) == NULL
443 +                || !handle_partial_dir(partialptr, PDIR_CREATE))
444 +                       return;
445 +               /* We only use the file if we can hard-link it into our tmp dir. */
446 +               if (link(fname, partialptr) != 0) {
447 +                       if (errno != EEXIST)
448 +                               handle_partial_dir(partialptr, PDIR_DELETE);
449 +                       return;
450 +               }
451 +       }
452 +
453 +       /* I think this falls into the -vv category with "%s is uptodate", etc. */
454 +       if (INFO_GTE(MISC, 2))
455 +               rprintf(FINFO, "found renamed: %s => %s\n", fname, fn);
456 +}
457 +
458  static inline int time_differs(struct file_struct *file, stat_x *sxp)
459  {
460         return cmp_time(sxp->st.st_mtime, file->modtime);
461 @@ -1139,6 +1279,7 @@ static void list_file_entry(struct file_struct *f)
462         }
463  }
464  
465 +static struct bitbag *delayed_bits = NULL;
466  static int phase = 0;
467  static int dflt_perms;
468  
469 @@ -1248,7 +1389,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
470                          && do_stat(dn, &sx.st) < 0) {
471                                 if (dry_run)
472                                         goto parent_is_dry_missing;
473 -                               if (make_path(fname, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0) {
474 +                               if (make_path(fname, ACCESSPERMS, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0) {
475                                         rsyserr(FERROR_XFER, errno,
476                                                 "recv_generator: mkdir %s failed",
477                                                 full_fname(dn));
478 @@ -1399,7 +1540,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
479                 }
480                 if (real_ret != 0 && do_mkdir(fname,file->mode|added_perms) < 0 && errno != EEXIST) {
481                         if (!relative_paths || errno != ENOENT
482 -                        || make_path(fname, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0
483 +                        || make_path(fname, ACCESSPERMS, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0
484                          || (do_mkdir(fname, file->mode|added_perms) < 0 && errno != EEXIST)) {
485                                 rsyserr(FERROR_XFER, errno,
486                                         "recv_generator: mkdir %s failed",
487 @@ -1448,9 +1589,12 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
488                 }
489                 else if (delete_during && f_out != -1 && !phase
490                     && !(file->flags & FLAG_MISSING_DIR)) {
491 -                       if (file->flags & FLAG_CONTENT_DIR)
492 -                               delete_in_dir(fname, file, &real_sx.st.st_dev);
493 -                       else
494 +                       if (file->flags & FLAG_CONTENT_DIR) {
495 +                               if (detect_renamed && real_ret != 0)
496 +                                       unexplored_dirs++;
497 +                               delete_in_dir(fname, file, &real_sx.st.st_dev,
498 +                                             delete_during < 0 ? DEL_NO_DELETIONS : 0);
499 +                       } else
500                                 change_local_filter_dir(fname, strlen(fname), F_DEPTH(file));
501                 }
502                 goto cleanup;
503 @@ -1715,8 +1859,14 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
504                         goto cleanup;
505                 }
506  #endif
507 -               if (stat_errno == ENOENT)
508 +               if (stat_errno == ENOENT) {
509 +                       if (detect_renamed && unexplored_dirs > 0
510 +                        && F_LENGTH(file)) {
511 +                               bitbag_set_bit(delayed_bits, ndx);
512 +                               return;
513 +                       }
514                         goto notify_others;
515 +               }
516                 rsyserr(FERROR_XFER, stat_errno, "recv_generator: failed to stat %s",
517                         full_fname(fname));
518                 goto cleanup;
519 @@ -2176,6 +2326,12 @@ void generate_files(int f_out, const char *local_name)
520         if (DEBUG_GTE(GENR, 1))
521                 rprintf(FINFO, "generator starting pid=%d\n", (int)getpid());
522  
523 +       if (detect_renamed) {
524 +               delayed_bits = bitbag_create(cur_flist->used);
525 +               if (!delete_before && !delete_during)
526 +                       delete_during = -1;
527 +       }
528 +
529         if (delete_before && !solo_file && cur_flist->used > 0)
530                 do_delete_pass();
531         if (delete_during == 2) {
532 @@ -2186,7 +2342,7 @@ void generate_files(int f_out, const char *local_name)
533         }
534         info_levels[INFO_FLIST] = info_levels[INFO_PROGRESS] = 0;
535  
536 -       if (append_mode > 0 || whole_file < 0)
537 +       if (append_mode > 0 || detect_renamed || whole_file < 0)
538                 whole_file = 0;
539         if (DEBUG_GTE(FLIST, 1)) {
540                 rprintf(FINFO, "delta-transmission %s\n",
541 @@ -2222,7 +2378,7 @@ void generate_files(int f_out, const char *local_name)
542                                                 dirdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
543                                         } else
544                                                 dirdev = MAKEDEV(0, 0);
545 -                                       delete_in_dir(fbuf, fp, &dirdev);
546 +                                       delete_in_dir(fbuf, fp, &dirdev, 0);
547                                 } else
548                                         change_local_filter_dir(fbuf, strlen(fbuf), F_DEPTH(fp));
549                         }
550 @@ -2269,7 +2425,21 @@ void generate_files(int f_out, const char *local_name)
551         } while ((cur_flist = cur_flist->next) != NULL);
552  
553         if (delete_during)
554 -               delete_in_dir(NULL, NULL, &dev_zero);
555 +               delete_in_dir(NULL, NULL, &dev_zero, 0);
556 +       if (detect_renamed) {
557 +               if (delete_during < 0)
558 +                       delete_during = 0;
559 +               detect_renamed = 0;
560 +
561 +               for (i = -1; (i = bitbag_next_bit(delayed_bits, i)) >= 0; ) {
562 +                       struct file_struct *file = cur_flist->files[i];
563 +                       if (local_name)
564 +                               strlcpy(fbuf, local_name, sizeof fbuf);
565 +                       else
566 +                               f_name(file, fbuf);
567 +                       recv_generator(fbuf, file, i, itemizing, code, f_out);
568 +               }
569 +       }
570         phase++;
571         if (DEBUG_GTE(GENR, 1))
572                 rprintf(FINFO, "generate_files phase=%d\n", phase);
573 diff --git a/main.c b/main.c
574 --- a/main.c
575 +++ b/main.c
576 @@ -850,7 +850,7 @@ static int do_recv(int f_in, int f_out, char *local_name)
577         }
578  
579         if (backup_dir) {
580 -               int ret = make_path(backup_dir_buf, MKP_DROP_NAME); /* drops trailing slash */
581 +               int ret = make_path(backup_dir_buf, ACCESSPERMS, MKP_DROP_NAME); /* drops trailing slash */
582                 if (ret < 0)
583                         exit_cleanup(RERR_SYNTAX);
584                 if (ret)
585 diff --git a/options.c b/options.c
586 --- a/options.c
587 +++ b/options.c
588 @@ -81,6 +81,7 @@ int am_server = 0;
589  int am_sender = 0;
590  int am_starting_up = 1;
591  int relative_paths = -1;
592 +int detect_renamed = 0;
593  int implied_dirs = 1;
594  int missing_args = 0; /* 0 = FERROR_XFER, 1 = ignore, 2 = delete */
595  int numeric_ids = 0;
596 @@ -758,6 +759,7 @@ void usage(enum logcode F)
597    rprintf(F,"     --modify-window=NUM     compare mod-times with reduced accuracy\n");
598    rprintf(F," -T, --temp-dir=DIR          create temporary files in directory DIR\n");
599    rprintf(F," -y, --fuzzy                 find similar file for basis if no dest file\n");
600 +  rprintf(F,"     --detect-renamed        try to find renamed files to speed up the transfer\n");
601    rprintf(F,"     --compare-dest=DIR      also compare destination files relative to DIR\n");
602    rprintf(F,"     --copy-dest=DIR         ... and include copies of unchanged files\n");
603    rprintf(F,"     --link-dest=DIR         hardlink to files in DIR when unchanged\n");
604 @@ -961,6 +963,7 @@ static struct poptOption long_options[] = {
605    {"compare-dest",     0,  POPT_ARG_STRING, 0, OPT_COMPARE_DEST, 0, 0 },
606    {"copy-dest",        0,  POPT_ARG_STRING, 0, OPT_COPY_DEST, 0, 0 },
607    {"link-dest",        0,  POPT_ARG_STRING, 0, OPT_LINK_DEST, 0, 0 },
608 +  {"detect-renamed",   0,  POPT_ARG_NONE,   &detect_renamed, 0, 0, 0 },
609    {"fuzzy",           'y', POPT_ARG_NONE,   0, 'y', 0, 0 },
610    {"no-fuzzy",         0,  POPT_ARG_VAL,    &fuzzy_basis, 0, 0, 0 },
611    {"no-y",             0,  POPT_ARG_VAL,    &fuzzy_basis, 0, 0, 0 },
612 @@ -2228,7 +2231,7 @@ int parse_arguments(int *argc_p, const char ***argv_p)
613                 inplace = 1;
614         }
615  
616 -       if (delay_updates && !partial_dir)
617 +       if ((delay_updates || detect_renamed) && !partial_dir)
618                 partial_dir = tmp_partialdir;
619  
620         if (inplace) {
621 @@ -2237,6 +2240,7 @@ int parse_arguments(int *argc_p, const char ***argv_p)
622                         snprintf(err_buf, sizeof err_buf,
623                                  "--%s cannot be used with --%s\n",
624                                  append_mode ? "append" : "inplace",
625 +                                detect_renamed ? "detect-renamed" :
626                                  delay_updates ? "delay-updates" : "partial-dir");
627                         return 0;
628                 }
629 @@ -2609,6 +2613,8 @@ void server_options(char **args, int *argc_p)
630                         args[ac++] = "--super";
631                 if (size_only)
632                         args[ac++] = "--size-only";
633 +               if (detect_renamed)
634 +                       args[ac++] = "--detect-renamed";
635                 if (do_stats)
636                         args[ac++] = "--stats";
637         } else {
638 diff --git a/receiver.c b/receiver.c
639 --- a/receiver.c
640 +++ b/receiver.c
641 @@ -208,7 +208,7 @@ int open_tmpfile(char *fnametmp, const char *fname, struct file_struct *file)
642          * information should have been previously transferred, but that may
643          * not be the case with -R */
644         if (fd == -1 && relative_paths && errno == ENOENT
645 -        && make_path(fnametmp, MKP_SKIP_SLASH | MKP_DROP_NAME) == 0) {
646 +        && make_path(fnametmp, ACCESSPERMS, MKP_SKIP_SLASH | MKP_DROP_NAME) == 0) {
647                 /* Get back to name with XXXXXX in it. */
648                 get_tmpname(fnametmp, fname, False);
649                 fd = do_mkstemp(fnametmp, (file->mode|added_perms) & INITACCESSPERMS);
650 diff --git a/rsync.h b/rsync.h
651 --- a/rsync.h
652 +++ b/rsync.h
653 @@ -251,7 +251,7 @@ enum msgcode {
654  #define NDX_DEL_STATS -3
655  #define NDX_FLIST_OFFSET -101
656  
657 -/* For calling delete_item() and delete_dir_contents(). */
658 +/* For calling delete_item(), delete_dir_contents(), and delete_in_dir(). */
659  #define DEL_NO_UID_WRITE       (1<<0) /* file/dir has our uid w/o write perm */
660  #define DEL_RECURSE            (1<<1) /* if dir, delete all contents */
661  #define DEL_DIR_IS_EMPTY       (1<<2) /* internal delete_FUNCTIONS use only */
662 @@ -261,6 +261,7 @@ enum msgcode {
663  #define DEL_FOR_DEVICE         (1<<6) /* making room for a replacement device */
664  #define DEL_FOR_SPECIAL        (1<<7) /* making room for a replacement special */
665  #define DEL_FOR_BACKUP         (1<<8) /* the delete is for a backup operation */
666 +#define DEL_NO_DELETIONS       (1<<9) /* just check for renames w/o deleting */
667  
668  #define DEL_MAKE_ROOM (DEL_FOR_FILE|DEL_FOR_DIR|DEL_FOR_SYMLINK|DEL_FOR_DEVICE|DEL_FOR_SPECIAL)
669  
670 diff --git a/rsync.yo b/rsync.yo
671 --- a/rsync.yo
672 +++ b/rsync.yo
673 @@ -413,6 +413,7 @@ to the detailed description below for a complete description.  verb(
674       --modify-window=NUM     compare mod-times with reduced accuracy
675   -T, --temp-dir=DIR          create temporary files in directory DIR
676   -y, --fuzzy                 find similar file for basis if no dest file
677 +     --detect-renamed        try to find renamed files to speed the xfer
678       --compare-dest=DIR      also compare received files relative to DIR
679       --copy-dest=DIR         ... and include copies of unchanged files
680       --link-dest=DIR         hardlink to files in DIR when unchanged
681 @@ -1768,6 +1769,21 @@ Note that the use of the bf(--delete) option might get rid of any potential
682  fuzzy-match files, so either use bf(--delete-after) or specify some
683  filename exclusions if you need to prevent this.
684  
685 +dit(bf(--detect-renamed)) With this option, for each new source file
686 +(call it em(src/S)), rsync looks for a file em(dest/D) anywhere in the
687 +destination that passes the quick check with em(src/S).  If such a em(dest/D)
688 +is found, rsync uses it as an alternate basis for transferring em(S).  The
689 +idea is that if em(src/S) was renamed from em(src/D) (as opposed to em(src/S)
690 +passing the quick check with em(dest/D) by coincidence), the delta-transfer
691 +algorithm will find that all the data matches between em(src/S) and em(dest/D),
692 +and the transfer will be really fast.
693 +
694 +By default, alternate-basis files are hard-linked into a directory named
695 +".~tmp~" in each file's destination directory, but if you've specified
696 +the bf(--partial-dir) option, that directory will be used instead.  These
697 +potential alternate-basis files will be removed as the transfer progresses.
698 +This option conflicts with bf(--inplace) and bf(--append).
699 +
700  dit(bf(--compare-dest=DIR)) This option instructs rsync to use em(DIR) on
701  the destination machine as an additional hierarchy to compare destination
702  files against doing transfers (if the files are missing in the destination
703 diff --git a/util.c b/util.c
704 --- a/util.c
705 +++ b/util.c
706 @@ -175,7 +175,7 @@ int set_modtime(const char *fname, time_t modtime, uint32 mod_nsec, mode_t mode)
707  /* Create any necessary directories in fname.  Any missing directories are
708   * created with default permissions.  Returns < 0 on error, or the number
709   * of directories created. */
710 -int make_path(char *fname, int flags)
711 +int make_path(char *fname, mode_t mode, int flags)
712  {
713         char *end, *p;
714         int ret = 0;
715 @@ -206,7 +206,7 @@ int make_path(char *fname, int flags)
716                                 else
717                                         errno = ENOTDIR;
718                         }
719 -               } else if (do_mkdir(fname, ACCESSPERMS) == 0) {
720 +               } else if (do_mkdir(fname, mode) == 0) {
721                         ret++;
722                         break;
723                 }
724 @@ -243,7 +243,7 @@ int make_path(char *fname, int flags)
725                 p += strlen(p);
726                 if (ret < 0) /* Skip mkdir on error, but keep restoring the path. */
727                         continue;
728 -               if (do_mkdir(fname, ACCESSPERMS) < 0)
729 +               if (do_mkdir(fname, mode) < 0)
730                         ret = -ret - 1;
731                 else
732                         ret++;
733 @@ -1125,6 +1125,32 @@ char *normalize_path(char *path, BOOL force_newbuf, unsigned int *len_ptr)
734         return path;
735  }
736  
737 +/* We need to supply our own strcmp function for file list comparisons
738 + * to ensure that signed/unsigned usage is consistent between machines. */
739 +int u_strcmp(const char *p1, const char *p2)
740 +{
741 +        for ( ; *p1; p1++, p2++) {
742 +               if (*p1 != *p2)
743 +                       break;
744 +       }
745 +
746 +       return (int)*(uchar*)p1 - (int)*(uchar*)p2;
747 +}
748 +
749 +/* We need a memcmp function compares unsigned-byte values. */
750 +int u_memcmp(const void *p1, const void *p2, size_t len)
751 +{
752 +       const uchar *u1 = p1;
753 +       const uchar *u2 = p2;
754 +
755 +       while (len--) {
756 +               if (*u1 != *u2)
757 +                       return (int)*u1 - (int)*u2;
758 +       }
759 +
760 +       return 0;
761 +}
762 +
763  /**
764   * Return a quoted string with the full pathname of the indicated filename.
765   * The string " (in MODNAME)" may also be appended.  The returned pointer
766 @@ -1218,7 +1244,7 @@ int handle_partial_dir(const char *fname, int create)
767                         }
768                         statret = -1;
769                 }
770 -               if (statret < 0 && do_mkdir(dir, 0700) < 0) {
771 +               if (statret < 0 && make_path(dir, 0700, 0) < 0) {
772                         *fn = '/';
773                         return 0;
774                 }