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