Update to latest source.
[rsync-patches.git] / checksum-reading.diff
1 Optimize the --checksum option using externally created .rsyncsums files.
2
3 This adds a new option, --sumfiles=MODE, that allows you to use a cache of
4 checksums when performing a --checksum transfer.  These checksum files
5 (.rsyncsums) must be created by some other process -- see the perl script,
6 rsyncsums, in the support dir for one way.
7
8 This option can be particularly helpful to a public mirror that wants to
9 pre-compute their .rsyncsums files, set the "checksum files = strict" option
10 in their daemon config file, and thus make it quite efficient for a client
11 rsync to make use of the --checksum option on their server.
12
13 To use this patch, run these commands for a successful build:
14
15     patch -p1 <patches/checksum-reading.diff
16     ./configure                               (optional if already run)
17     make
18
19 based-on: fe2ef556d9ef11e5dd549e19a06a7a924f7ddfa1
20 diff --git a/clientserver.c b/clientserver.c
21 --- a/clientserver.c
22 +++ b/clientserver.c
23 @@ -43,6 +43,8 @@ extern int numeric_ids;
24  extern int filesfrom_fd;
25  extern int remote_protocol;
26  extern int protocol_version;
27 +extern int always_checksum;
28 +extern int checksum_files;
29  extern int io_timeout;
30  extern int no_detach;
31  extern int write_batch;
32 @@ -1015,6 +1017,9 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char
33         } else if (am_root < 0) /* Treat --fake-super from client as --super. */
34                 am_root = 2;
35  
36 +       checksum_files = always_checksum ? lp_checksum_files(i)
37 +                                        : CSF_IGNORE_FILES;
38 +
39         if (filesfrom_fd == 0)
40                 filesfrom_fd = f_in;
41  
42 diff --git a/flist.c b/flist.c
43 --- a/flist.c
44 +++ b/flist.c
45 @@ -22,6 +22,7 @@
46  
47  #include "rsync.h"
48  #include "ifuncs.h"
49 +#include "itypes.h"
50  #include "rounding.h"
51  #include "inums.h"
52  #include "io.h"
53 @@ -33,6 +34,7 @@ extern int am_sender;
54  extern int am_generator;
55  extern int inc_recurse;
56  extern int always_checksum;
57 +extern int basis_dir_cnt;
58  extern int checksum_type;
59  extern int module_id;
60  extern int ignore_errors;
61 @@ -61,6 +63,7 @@ extern int implied_dirs;
62  extern int ignore_perishable;
63  extern int non_perishable_cnt;
64  extern int prune_empty_dirs;
65 +extern int checksum_files;
66  extern int copy_links;
67  extern int copy_unsafe_links;
68  extern int protocol_version;
69 @@ -72,6 +75,7 @@ extern int sender_symlink_iconv;
70  extern int output_needs_newline;
71  extern int sender_keeps_checksum;
72  extern int unsort_ndx;
73 +extern char *basis_dir[];
74  extern uid_t our_uid;
75  extern struct stats stats;
76  extern char *filesfrom_host;
77 @@ -89,6 +93,20 @@ extern int filesfrom_convert;
78  extern iconv_t ic_send, ic_recv;
79  #endif
80  
81 +#ifdef HAVE_UTIMENSAT
82 +#ifdef HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
83 +#define ST_MTIME_NSEC st_mtim.tv_nsec
84 +#elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
85 +#define ST_MTIME_NSEC st_mtimensec
86 +#endif
87 +#endif
88 +
89 +#define RSYNCSUMS_FILE ".rsyncsums"
90 +#define RSYNCSUMS_LEN (sizeof RSYNCSUMS_FILE-1)
91 +
92 +#define CLEAN_STRIP_ROOT (1<<0)
93 +#define CLEAN_KEEP_LAST (1<<1)
94 +
95  #define PTR_SIZE (sizeof (struct file_struct *))
96  
97  int io_error;
98 @@ -133,7 +151,11 @@ static char empty_sum[MAX_DIGEST_LEN];
99  static int flist_count_offset; /* for --delete --progress */
100  static int show_filelist_progress;
101  
102 -static void flist_sort_and_clean(struct file_list *flist, int strip_root);
103 +static struct csum_cache {
104 +       struct file_list *flist;
105 +} *csum_cache = NULL;
106 +
107 +static void flist_sort_and_clean(struct file_list *flist, int flags);
108  static void output_flist(struct file_list *flist);
109  
110  void init_flist(void)
111 @@ -322,6 +344,235 @@ static void flist_done_allocating(struct file_list *flist)
112                 flist->pool_boundary = ptr;
113  }
114  
115 +void reset_checksum_cache()
116 +{
117 +       int slot, slots = am_sender ? 1 : basis_dir_cnt + 1;
118 +
119 +       if (!csum_cache)
120 +               csum_cache = new_array0(struct csum_cache, slots);
121 +
122 +       for (slot = 0; slot < slots; slot++) {
123 +               struct file_list *flist = csum_cache[slot].flist;
124 +
125 +               if (flist) {
126 +                       /* Reset the pool memory and empty the file-list array. */
127 +                       pool_free_old(flist->file_pool,
128 +                                     pool_boundary(flist->file_pool, 0));
129 +                       flist->used = 0;
130 +               } else
131 +                       flist = csum_cache[slot].flist = flist_new(FLIST_TEMP, "reset_checksum_cache");
132 +
133 +               flist->low = 0;
134 +               flist->high = -1;
135 +               flist->next = NULL;
136 +       }
137 +}
138 +
139 +/* The basename_len count is the length of the basename + 1 for the '\0'. */
140 +static int add_checksum(struct file_list *flist, const char *dirname,
141 +                       const char *basename, int basename_len, OFF_T file_length,
142 +                       time_t mtime, uint32 ctime, uint32 inode,
143 +                       const char *sum)
144 +{
145 +       struct file_struct *file;
146 +       int alloc_len, extra_len;
147 +       char *bp;
148 +
149 +       if (basename_len == RSYNCSUMS_LEN+1 && *basename == '.'
150 +        && strcmp(basename, RSYNCSUMS_FILE) == 0)
151 +               return 0;
152 +
153 +       /* "2" is for a 32-bit ctime num and an 32-bit inode num. */
154 +       extra_len = (file_extra_cnt + (file_length > 0xFFFFFFFFu) + SUM_EXTRA_CNT + 2)
155 +                 * EXTRA_LEN;
156 +#if EXTRA_ROUNDING > 0
157 +       if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
158 +               extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
159 +#endif
160 +       alloc_len = FILE_STRUCT_LEN + extra_len + basename_len;
161 +       bp = pool_alloc(flist->file_pool, alloc_len, "add_checksum");
162 +
163 +       memset(bp, 0, extra_len + FILE_STRUCT_LEN);
164 +       bp += extra_len;
165 +       file = (struct file_struct *)bp;
166 +       bp += FILE_STRUCT_LEN;
167 +
168 +       memcpy(bp, basename, basename_len);
169 +
170 +       file->mode = S_IFREG;
171 +       file->modtime = mtime;
172 +       file->len32 = (uint32)file_length;
173 +       if (file_length > 0xFFFFFFFFu) {
174 +               file->flags |= FLAG_LENGTH64;
175 +               OPT_EXTRA(file, 0)->unum = (uint32)(file_length >> 32);
176 +       }
177 +       file->dirname = dirname;
178 +       F_CTIME(file) = ctime;
179 +       F_INODE(file) = inode;
180 +       bp = F_SUM(file);
181 +       memcpy(bp, sum, flist_csum_len);
182 +
183 +       flist_expand(flist, 1);
184 +       flist->files[flist->used++] = file;
185 +
186 +       flist->sorted = flist->files;
187 +
188 +       return 1;
189 +}
190 +
191 +/* The "dirname" arg's data must remain unchanged during the lifespan of
192 + * the created csum_cache[].flist object because we use it directly. */
193 +static void read_checksums(int slot, struct file_list *flist, const char *dirname)
194 +{
195 +       char line[MAXPATHLEN+1024], fbuf[MAXPATHLEN], sum[MAX_DIGEST_LEN];
196 +       FILE *fp;
197 +       char *cp;
198 +       int len, i;
199 +       time_t mtime;
200 +       OFF_T file_length;
201 +       uint32 ctime, inode;
202 +       int dlen = dirname ? strlcpy(fbuf, dirname, sizeof fbuf) : 0;
203 +
204 +       if (dlen >= (int)(sizeof fbuf - 1 - RSYNCSUMS_LEN))
205 +               return;
206 +       if (dlen)
207 +               fbuf[dlen++] = '/';
208 +       else
209 +               dirname = NULL;
210 +       strlcpy(fbuf+dlen, RSYNCSUMS_FILE, sizeof fbuf - dlen);
211 +       if (slot) {
212 +               pathjoin(line, sizeof line, basis_dir[slot-1], fbuf);
213 +               cp = line;
214 +       } else
215 +               cp = fbuf;
216 +       if (!(fp = fopen(cp, "r")))
217 +               return;
218 +
219 +       while (fgets(line, sizeof line, fp)) {
220 +               cp = line;
221 +               if (checksum_type == 5) {
222 +                       char *alt_sum = cp;
223 +                       if (*cp == '=')
224 +                               while (*++cp == '=') {}
225 +                       else
226 +                               while (isHexDigit(cp)) cp++;
227 +                       if (cp - alt_sum != MD4_DIGEST_LEN*2 || *cp != ' ')
228 +                               break;
229 +                       while (*++cp == ' ') {}
230 +               }
231 +
232 +               if (*cp == '=') {
233 +                       continue;
234 +               } else {
235 +                       for (i = 0; i < flist_csum_len*2; i++, cp++) {
236 +                               int x;
237 +                               if (isHexDigit(cp)) {
238 +                                       if (isDigit(cp))
239 +                                               x = *cp - '0';
240 +                                       else
241 +                                               x = (*cp & 0xF) + 9;
242 +                               } else {
243 +                                       cp = "";
244 +                                       break;
245 +                               }
246 +                               if (i & 1)
247 +                                       sum[i/2] |= x;
248 +                               else
249 +                                       sum[i/2] = x << 4;
250 +                       }
251 +               }
252 +               if (*cp != ' ')
253 +                       break;
254 +               while (*++cp == ' ') {}
255 +
256 +               if (checksum_type != 5) {
257 +                       char *alt_sum = cp;
258 +                       if (*cp == '=')
259 +                               while (*++cp == '=') {}
260 +                       else
261 +                               while (isHexDigit(cp)) cp++;
262 +                       if (cp - alt_sum != MD5_DIGEST_LEN*2 || *cp != ' ')
263 +                               break;
264 +                       while (*++cp == ' ') {}
265 +               }
266 +
267 +               file_length = 0;
268 +               while (isDigit(cp))
269 +                       file_length = file_length * 10 + *cp++ - '0';
270 +               if (*cp != ' ')
271 +                       break;
272 +               while (*++cp == ' ') {}
273 +
274 +               mtime = 0;
275 +               while (isDigit(cp))
276 +                       mtime = mtime * 10 + *cp++ - '0';
277 +               if (*cp != ' ')
278 +                       break;
279 +               while (*++cp == ' ') {}
280 +
281 +               ctime = 0;
282 +               while (isDigit(cp))
283 +                       ctime = ctime * 10 + *cp++ - '0';
284 +               if (*cp != ' ')
285 +                       break;
286 +               while (*++cp == ' ') {}
287 +
288 +               inode = 0;
289 +               while (isDigit(cp))
290 +                       inode = inode * 10 + *cp++ - '0';
291 +               if (*cp != ' ')
292 +                       break;
293 +               while (*++cp == ' ') {}
294 +
295 +               len = strlen(cp);
296 +               while (len && (cp[len-1] == '\n' || cp[len-1] == '\r'))
297 +                       len--;
298 +               if (!len)
299 +                       break;
300 +               cp[len++] = '\0'; /* len now counts the null */
301 +               if (strchr(cp, '/'))
302 +                       break;
303 +               if (len > MAXPATHLEN)
304 +                       continue;
305 +
306 +               strlcpy(fbuf+dlen, cp, sizeof fbuf - dlen);
307 +
308 +               add_checksum(flist, dirname, cp, len, file_length,
309 +                            mtime, ctime, inode,
310 +                            sum);
311 +       }
312 +       fclose(fp);
313 +
314 +       flist_sort_and_clean(flist, CLEAN_KEEP_LAST);
315 +}
316 +
317 +void get_cached_checksum(int slot, const char *fname, struct file_struct *file,
318 +                        STRUCT_STAT *stp, char *sum_buf)
319 +{
320 +       struct file_list *flist = csum_cache[slot].flist;
321 +       int j;
322 +
323 +       if (!flist->next) {
324 +               flist->next = cur_flist; /* next points from checksum flist to file flist */
325 +               read_checksums(slot, flist, file->dirname);
326 +       }
327 +
328 +       if ((j = flist_find(flist, file)) >= 0) {
329 +               struct file_struct *fp = flist->sorted[j];
330 +
331 +               if (F_LENGTH(fp) == stp->st_size
332 +                && fp->modtime == stp->st_mtime
333 +                && (checksum_files & CSF_LAX
334 +                 || (F_CTIME(fp) == (uint32)stp->st_ctime
335 +                  && F_INODE(fp) == (uint32)stp->st_ino))) {
336 +                       memcpy(sum_buf, F_SUM(fp), MAX_DIGEST_LEN);
337 +                       return;
338 +               }
339 +       }
340 +
341 +       file_checksum(fname, stp, sum_buf);
342 +}
343 +
344  /* Call this with EITHER (1) "file, NULL, 0" to chdir() to the file's
345   * F_PATHNAME(), or (2) "NULL, dir, dirlen" to chdir() to the supplied dir,
346   * with dir == NULL taken to be the starting directory, and dirlen < 0
347 @@ -1150,7 +1401,7 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
348                               STRUCT_STAT *stp, int flags, int filter_level)
349  {
350         static char *lastdir;
351 -       static int lastdir_len = -1;
352 +       static int lastdir_len = -2;
353         struct file_struct *file;
354         char thisname[MAXPATHLEN];
355         char linkname[MAXPATHLEN];
356 @@ -1296,9 +1547,16 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
357                         memcpy(lastdir, thisname, len);
358                         lastdir[len] = '\0';
359                         lastdir_len = len;
360 +                       if (checksum_files && am_sender && flist)
361 +                               reset_checksum_cache();
362                 }
363 -       } else
364 +       } else {
365                 basename = thisname;
366 +               if (checksum_files && am_sender && flist && lastdir_len == -2) {
367 +                       lastdir_len = -1;
368 +                       reset_checksum_cache();
369 +               }
370 +       }
371         basename_len = strlen(basename) + 1; /* count the '\0' */
372  
373  #ifdef SUPPORT_LINKS
374 @@ -1316,11 +1574,8 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
375                 extra_len += EXTRA_LEN;
376  #endif
377  
378 -       if (always_checksum && am_sender && S_ISREG(st.st_mode)) {
379 -               file_checksum(thisname, &st, tmp_sum);
380 -               if (sender_keeps_checksum)
381 -                       extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
382 -       }
383 +       if (sender_keeps_checksum && S_ISREG(st.st_mode))
384 +               extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
385  
386  #if EXTRA_ROUNDING > 0
387         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
388 @@ -1405,8 +1660,14 @@ struct file_struct *make_file(const char *fname, struct file_list *flist,
389                 return NULL;
390         }
391  
392 -       if (sender_keeps_checksum && S_ISREG(st.st_mode))
393 -               memcpy(F_SUM(file), tmp_sum, flist_csum_len);
394 +       if (always_checksum && am_sender && S_ISREG(st.st_mode)) {
395 +               if (flist && checksum_files)
396 +                       get_cached_checksum(0, thisname, file, &st, tmp_sum);
397 +               else
398 +                       file_checksum(thisname, &st, tmp_sum);
399 +               if (sender_keeps_checksum)
400 +                       memcpy(F_SUM(file), tmp_sum, flist_csum_len);
401 +       }
402  
403         if (unsort_ndx)
404                 F_NDX(file) = stats.num_dirs;
405 @@ -2621,7 +2882,7 @@ struct file_list *recv_file_list(int f, int dir_ndx)
406         /* The --relative option sends paths with a leading slash, so we need
407          * to specify the strip_root option here.  We rejected leading slashes
408          * for a non-relative transfer in recv_file_entry(). */
409 -       flist_sort_and_clean(flist, relative_paths);
410 +       flist_sort_and_clean(flist, relative_paths ? CLEAN_STRIP_ROOT : 0);
411  
412         if (protocol_version < 30) {
413                 /* Recv the io_error flag */
414 @@ -2871,7 +3132,7 @@ void flist_free(struct file_list *flist)
415  
416  /* This routine ensures we don't have any duplicate names in our file list.
417   * duplicate names can cause corruption because of the pipelining. */
418 -static void flist_sort_and_clean(struct file_list *flist, int strip_root)
419 +static void flist_sort_and_clean(struct file_list *flist, int flags)
420  {
421         char fbuf[MAXPATHLEN];
422         int i, prev_i;
423 @@ -2922,7 +3183,7 @@ static void flist_sort_and_clean(struct file_list *flist, int strip_root)
424                         /* If one is a dir and the other is not, we want to
425                          * keep the dir because it might have contents in the
426                          * list.  Otherwise keep the first one. */
427 -                       if (S_ISDIR(file->mode)) {
428 +                       if (S_ISDIR(file->mode) || flags & CLEAN_KEEP_LAST) {
429                                 struct file_struct *fp = flist->sorted[j];
430                                 if (!S_ISDIR(fp->mode))
431                                         keep = i, drop = j;
432 @@ -2938,8 +3199,8 @@ static void flist_sort_and_clean(struct file_list *flist, int strip_root)
433                         } else
434                                 keep = j, drop = i;
435  
436 -                       if (!am_sender) {
437 -                               if (DEBUG_GTE(DUP, 1)) {
438 +                       if (!am_sender || flags & CLEAN_KEEP_LAST) {
439 +                               if (DEBUG_GTE(DUP, 1) && !(flags & CLEAN_KEEP_LAST)) {
440                                         rprintf(FINFO,
441                                             "removing duplicate name %s from file list (%d)\n",
442                                             f_name(file, fbuf), drop + flist->ndx_start);
443 @@ -2961,7 +3222,7 @@ static void flist_sort_and_clean(struct file_list *flist, int strip_root)
444         }
445         flist->high = prev_i;
446  
447 -       if (strip_root) {
448 +       if (flags & CLEAN_STRIP_ROOT) {
449                 /* We need to strip off the leading slashes for relative
450                  * paths, but this must be done _after_ the sorting phase. */
451                 for (i = flist->low; i <= flist->high; i++) {
452 diff --git a/generator.c b/generator.c
453 --- a/generator.c
454 +++ b/generator.c
455 @@ -52,6 +52,7 @@ extern int delete_after;
456  extern int missing_args;
457  extern int msgdone_cnt;
458  extern int ignore_errors;
459 +extern int checksum_files;
460  extern int remove_source_files;
461  extern int delay_updates;
462  extern int update_only;
463 @@ -580,7 +581,7 @@ void itemize(const char *fnamecmp, struct file_struct *file, int ndx, int statre
464  
465  
466  /* Perform our quick-check heuristic for determining if a file is unchanged. */
467 -int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
468 +int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st, int slot)
469  {
470         if (st->st_size != F_LENGTH(file))
471                 return 0;
472 @@ -589,7 +590,10 @@ int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
473            of the file time to determine whether to sync */
474         if (always_checksum > 0 && S_ISREG(st->st_mode)) {
475                 char sum[MAX_DIGEST_LEN];
476 -               file_checksum(fn, st, sum);
477 +               if (checksum_files && slot >= 0)
478 +                       get_cached_checksum(slot, fn, file, st, sum);
479 +               else
480 +                       file_checksum(fn, st, sum);
481                 return memcmp(sum, F_SUM(file), flist_csum_len) == 0;
482         }
483  
484 @@ -886,7 +890,7 @@ static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
485                         best_match = j;
486                         match_level = 1;
487                 }
488 -               if (!unchanged_file(cmpbuf, file, &sxp->st))
489 +               if (!unchanged_file(cmpbuf, file, &sxp->st, j+1))
490                         continue;
491                 if (match_level == 1) {
492                         best_match = j;
493 @@ -1197,7 +1201,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
494          * --ignore-non-existing, daemon exclude, or mkdir failure. */
495         static struct file_struct *skip_dir = NULL;
496         static struct file_list *fuzzy_dirlist[MAX_BASIS_DIRS+1];
497 -       static int need_fuzzy_dirlist = 0;
498 +       static int need_new_dirscan = 0;
499         struct file_struct *fuzzy_file = NULL;
500         int fd = -1, f_copy = -1;
501         stat_x sx, real_sx;
502 @@ -1308,8 +1312,9 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
503                                                 fuzzy_dirlist[i] = NULL;
504                                         }
505                                 }
506 -                               need_fuzzy_dirlist = 1;
507 -                       }
508 +                               need_new_dirscan = 1;
509 +                       } else if (checksum_files)
510 +                               need_new_dirscan = 1;
511  #ifdef SUPPORT_ACLS
512                         if (!preserve_perms)
513                                 dflt_perms = default_perms_for_dir(dn);
514 @@ -1317,6 +1322,24 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
515                 }
516                 parent_dirname = dn;
517  
518 +               if (need_new_dirscan && S_ISREG(file->mode)) {
519 +                       int i;
520 +                       strlcpy(fnamecmpbuf, dn, sizeof fnamecmpbuf);
521 +                       for (i = 0; i < fuzzy_basis; i++) {
522 +                               if (i && pathjoin(fnamecmpbuf, MAXPATHLEN, basis_dir[i-1], dn) >= MAXPATHLEN)
523 +                                       continue;
524 +                               fuzzy_dirlist[i] = get_dirlist(fnamecmpbuf, -1, GDL_IGNORE_FILTER_RULES | GDL_PERHAPS_DIR);
525 +                               if (fuzzy_dirlist[i] && fuzzy_dirlist[i]->used == 0) {
526 +                                       flist_free(fuzzy_dirlist[i]);
527 +                                       fuzzy_dirlist[i] = NULL;
528 +                               }
529 +                       }
530 +                       if (checksum_files) {
531 +                               reset_checksum_cache();
532 +                       }
533 +                       need_new_dirscan = 0;
534 +               }
535 +
536                 statret = link_stat(fname, &sx.st, keep_dirlinks && is_dir);
537                 stat_errno = errno;
538         }
539 @@ -1720,22 +1743,6 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
540                 partialptr = NULL;
541  
542         if (statret != 0 && fuzzy_basis) {
543 -               if (need_fuzzy_dirlist && S_ISREG(file->mode)) {
544 -                       const char *dn = file->dirname ? file->dirname : ".";
545 -                       int i;
546 -                       strlcpy(fnamecmpbuf, dn, sizeof fnamecmpbuf);
547 -                       for (i = 0; i < fuzzy_basis; i++) {
548 -                               if (i && pathjoin(fnamecmpbuf, MAXPATHLEN, basis_dir[i-1], dn) >= MAXPATHLEN)
549 -                                       continue;
550 -                               fuzzy_dirlist[i] = get_dirlist(fnamecmpbuf, -1, GDL_IGNORE_FILTER_RULES | GDL_PERHAPS_DIR);
551 -                               if (fuzzy_dirlist[i] && fuzzy_dirlist[i]->used == 0) {
552 -                                       flist_free(fuzzy_dirlist[i]);
553 -                                       fuzzy_dirlist[i] = NULL;
554 -                               }
555 -                       }
556 -                       need_fuzzy_dirlist = 0;
557 -               }
558 -
559                 /* Sets fnamecmp_type to FNAMECMP_FUZZY or above. */
560                 fuzzy_file = find_fuzzy(file, fuzzy_dirlist, &fnamecmp_type);
561                 if (fuzzy_file) {
562 @@ -1768,7 +1775,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
563                 ;
564         else if (fnamecmp_type >= FNAMECMP_FUZZY)
565                 ;
566 -       else if (unchanged_file(fnamecmp, file, &sx.st)) {
567 +       else if (unchanged_file(fnamecmp, file, &sx.st, fnamecmp_type == FNAMECMP_FNAME ? 0 : -1)) {
568                 if (partialptr) {
569                         do_unlink(partialptr);
570                         handle_partial_dir(partialptr, PDIR_DELETE);
571 diff --git a/hlink.c b/hlink.c
572 --- a/hlink.c
573 +++ b/hlink.c
574 @@ -406,7 +406,7 @@ int hard_link_check(struct file_struct *file, int ndx, char *fname,
575                                 }
576                                 break;
577                         }
578 -                       if (!unchanged_file(cmpbuf, file, &alt_sx.st))
579 +                       if (!unchanged_file(cmpbuf, file, &alt_sx.st, j+1))
580                                 continue;
581                         statret = 1;
582                         if (unchanged_attrs(cmpbuf, file, &alt_sx))
583 diff --git a/loadparm.c b/loadparm.c
584 --- a/loadparm.c
585 +++ b/loadparm.c
586 @@ -174,6 +174,7 @@ typedef struct {
587         BOOL temp_dir_EXP;
588         BOOL uid_EXP;
589  
590 +       int checksum_files;
591         int max_connections;
592         int max_verbosity;
593         int syslog_facility;
594 @@ -291,6 +292,7 @@ static const all_vars Defaults = {
595   /* temp_dir_EXP; */           False,
596   /* uid_EXP; */                        False,
597  
598 + /* checksum_files; */         CSF_IGNORE_FILES,
599   /* max_connections; */                0,
600   /* max_verbosity; */          1,
601   /* syslog_facility; */                LOG_DAEMON,
602 @@ -393,6 +395,13 @@ static struct enum_list enum_facilities[] = {
603         { -1, NULL }
604  };
605  
606 +static struct enum_list enum_csum_modes[] = {
607 +       { CSF_IGNORE_FILES, "none" },
608 +       { CSF_LAX_MODE, "lax" },
609 +       { CSF_STRICT_MODE, "strict" },
610 +       { -1, NULL }
611 +};
612 +
613  static struct parm_struct parm_table[] =
614  {
615   {"address",           P_STRING, P_GLOBAL,&Vars.g.bind_address,        NULL,0},
616 @@ -408,6 +417,7 @@ static struct parm_struct parm_table[] =
617  
618   {"auth users",        P_STRING, P_LOCAL, &Vars.l.auth_users,          NULL,0},
619   {"charset",           P_STRING, P_LOCAL, &Vars.l.charset,             NULL,0},
620 + {"checksum files",    P_ENUM,   P_LOCAL, &Vars.l.checksum_files,      enum_csum_modes,0},
621   {"comment",           P_STRING, P_LOCAL, &Vars.l.comment,             NULL,0},
622   {"dont compress",     P_STRING, P_LOCAL, &Vars.l.dont_compress,       NULL,0},
623   {"early exec",        P_STRING, P_LOCAL, &Vars.l.early_exec,          NULL,0},
624 @@ -575,6 +585,7 @@ FN_LOCAL_STRING(lp_syslog_tag, syslog_tag)
625  FN_LOCAL_STRING(lp_temp_dir, temp_dir)
626  FN_LOCAL_STRING(lp_uid, uid)
627  
628 +FN_LOCAL_INTEGER(lp_checksum_files, checksum_files)
629  FN_LOCAL_INTEGER(lp_max_connections, max_connections)
630  FN_LOCAL_INTEGER(lp_max_verbosity, max_verbosity)
631  FN_LOCAL_INTEGER(lp_syslog_facility, syslog_facility)
632 diff --git a/options.c b/options.c
633 --- a/options.c
634 +++ b/options.c
635 @@ -119,6 +119,7 @@ size_t bwlimit_writemax = 0;
636  int ignore_existing = 0;
637  int ignore_non_existing = 0;
638  int need_messages_from_generator = 0;
639 +int checksum_files = CSF_IGNORE_FILES;
640  int max_delete = INT_MIN;
641  OFF_T max_size = -1;
642  OFF_T min_size = -1;
643 @@ -782,7 +783,7 @@ enum {OPT_SERVER = 1000, OPT_DAEMON, OPT_SENDER, OPT_EXCLUDE, OPT_EXCLUDE_FROM,
644        OPT_FILTER, OPT_COMPARE_DEST, OPT_COPY_DEST, OPT_LINK_DEST, OPT_HELP,
645        OPT_INCLUDE, OPT_INCLUDE_FROM, OPT_MODIFY_WINDOW, OPT_MIN_SIZE, OPT_CHMOD,
646        OPT_READ_BATCH, OPT_WRITE_BATCH, OPT_ONLY_WRITE_BATCH, OPT_MAX_SIZE,
647 -      OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG,
648 +      OPT_NO_D, OPT_APPEND, OPT_NO_ICONV, OPT_INFO, OPT_DEBUG, OPT_SUMFILES,
649        OPT_USERMAP, OPT_GROUPMAP, OPT_CHOWN, OPT_BWLIMIT,
650        OPT_OLD_COMPRESS, OPT_NEW_COMPRESS, OPT_NO_COMPRESS,
651        OPT_REFUSED_BASE = 9000};
652 @@ -934,6 +935,7 @@ static struct poptOption long_options[] = {
653    {"no-c",             0,  POPT_ARG_VAL,    &always_checksum, 0, 0, 0 },
654    {"checksum-choice",  0,  POPT_ARG_STRING, &checksum_choice, 0, 0, 0 },
655    {"cc",               0,  POPT_ARG_STRING, &checksum_choice, 0, 0, 0 },
656 +  {"sumfiles",         0,  POPT_ARG_STRING, 0, OPT_SUMFILES, 0, 0 },
657    {"block-size",      'B', POPT_ARG_LONG,   &block_size, 0, 0, 0 },
658    {"compare-dest",     0,  POPT_ARG_STRING, 0, OPT_COMPARE_DEST, 0, 0 },
659    {"copy-dest",        0,  POPT_ARG_STRING, 0, OPT_COPY_DEST, 0, 0 },
660 @@ -1757,6 +1759,23 @@ int parse_arguments(int *argc_p, const char ***argv_p)
661                         }
662                         break;
663  
664 +               case OPT_SUMFILES:
665 +                       arg = poptGetOptArg(pc);
666 +                       checksum_files = 0;
667 +                       if (strcmp(arg, "lax") == 0)
668 +                               checksum_files |= CSF_LAX_MODE;
669 +                       else if (strcmp(arg, "strict") == 0)
670 +                               checksum_files |= CSF_STRICT_MODE;
671 +                       else if (strcmp(arg, "none") == 0)
672 +                               checksum_files = CSF_IGNORE_FILES;
673 +                       else {
674 +                               snprintf(err_buf, sizeof err_buf,
675 +                                   "Invalid argument passed to --sumfiles (%s)\n",
676 +                                   arg);
677 +                               return 0;
678 +                       }
679 +                       break;
680 +
681                 case OPT_INFO:
682                         arg = poptGetOptArg(pc);
683                         parse_output_words(info_words, info_levels, arg, USER_PRIORITY);
684 @@ -2043,6 +2062,9 @@ int parse_arguments(int *argc_p, const char ***argv_p)
685         }
686  #endif
687  
688 +       if (!always_checksum)
689 +               checksum_files = CSF_IGNORE_FILES;
690 +
691         if (block_size) {
692                 /* We may not know the real protocol_version at this point if this is the client
693                  * option parsing, but we still want to check it so that the client can specify
694 diff --git a/rsync.1.md b/rsync.1.md
695 --- a/rsync.1.md
696 +++ b/rsync.1.md
697 @@ -338,6 +338,7 @@ detailed description below for a complete description.
698  --quiet, -q              suppress non-error messages
699  --no-motd                suppress daemon-mode MOTD
700  --checksum, -c           skip based on checksum, not mod-time & size
701 +--sumfiles=MODE          use .rsyncsums to speedup --checksum mode
702  --archive, -a            archive mode; equals -rlptgoD (no -H,-A,-X)
703  --no-OPTION              turn off an implied OPTION (e.g. --no-D)
704  --recursive, -r          recurse into directories
705 @@ -684,6 +685,8 @@ your home directory (remove the '=' for that).
706      file that has the same size as the corresponding sender's file: files with
707      either a changed size or a changed checksum are selected for transfer.
708  
709 +    See also the `--sumfiles` option for a way to use cached checksum data.
710 +
711      Note that rsync always verifies that each _transferred_ file was correctly
712      reconstructed on the receiving side by checking a whole-file checksum that
713      is generated as the file is transferred, but that automatic
714 @@ -694,6 +697,38 @@ your home directory (remove the '=' for that).
715      can be overridden using either the `--checksum-choice` option or an
716      environment variable that is discussed in that option's section.
717  
718 +0.  `--sumfiles=MODE`
719 +
720 +    This option tells rsync to make use of any cached checksum information it
721 +    finds in per-directory .rsyncsums files when the current transfer is using
722 +    the `--checksum` option.  If the checksum data is up-to-date, it is used
723 +    instead of recomputing it, saving both disk I/O and CPU time.  If the
724 +    checksum data is missing or outdated, the checksum is computed just as it
725 +    would be if `--sumfiles` was not specified.
726 +
727 +    The MODE value is either "lax", for relaxed checking (which compares size
728 +    and mtime), "strict" (which also compares ctime and inode), or "none" to
729 +    ignore any .rsyncsums files ("none" is the default).  Rsync does not create
730 +    or update these files, but there is a perl script in the support directory
731 +    named "rsyncsums" that can be used for that.
732 +
733 +    This option has no effect unless `--checksum`, `-c` was also specified.  It
734 +    also only affects the current side of the transfer, so if you want the
735 +    remote side to parse its own .rsyncsums files, specify the option via the
736 +    `--rsync-path` option (e.g. "--rsync-path="rsync --sumfiles=lax").
737 +
738 +    To avoid transferring the system's checksum files, you can use an exclude
739 +    (e.g. `--exclude=.rsyncsums`).  To make this easier to type, you can use a
740 +    popt alias.  For instance, adding the following line in your ~/.popt file
741 +    defines a `--cc` option that enables lax checksum files and excludes the
742 +    checksum files:
743 +
744 +    >     rsync alias --cc -c --sumfiles=lax --exclude=.rsyncsums
745 +
746 +    An rsync daemon does not allow the client to control this setting, so see
747 +    the "checksum files" daemon parameter for information on how to make a
748 +    daemon use cached checksum data.
749 +
750  0.  `--archive`, `-a`
751  
752      This is equivalent to `-rlptgoD`.  It is a quick way of saying you want
753 diff --git a/rsync.h b/rsync.h
754 --- a/rsync.h
755 +++ b/rsync.h
756 @@ -834,6 +834,10 @@ extern int xattrs_ndx;
757  #define F_SUM(f) ((char*)OPT_EXTRA(f, START_BUMP(f) + HLINK_BUMP(f) \
758                                     + SUM_EXTRA_CNT - 1))
759  
760 +/* These are only valid on an entry read from a checksum file. */
761 +#define F_CTIME(f) OPT_EXTRA(f, LEN64_BUMP(f) + SUM_EXTRA_CNT)->unum
762 +#define F_INODE(f) OPT_EXTRA(f, LEN64_BUMP(f) + SUM_EXTRA_CNT + 1)->unum
763 +
764  /* Some utility defines: */
765  #define F_IS_ACTIVE(f) (f)->basename[0]
766  #define F_IS_HLINKED(f) ((f)->flags & FLAG_HLINKED)
767 @@ -1036,6 +1040,13 @@ typedef struct {
768         char fname[1]; /* has variable size */
769  } relnamecache;
770  
771 +#define CSF_ENABLE (1<<1)
772 +#define CSF_LAX (1<<2)
773 +
774 +#define CSF_IGNORE_FILES 0
775 +#define CSF_LAX_MODE (CSF_ENABLE|CSF_LAX)
776 +#define CSF_STRICT_MODE (CSF_ENABLE)
777 +
778  #include "byteorder.h"
779  #include "lib/mdigest.h"
780  #include "lib/wildmatch.h"
781 diff --git a/rsyncd.conf.5.md b/rsyncd.conf.5.md
782 --- a/rsyncd.conf.5.md
783 +++ b/rsyncd.conf.5.md
784 @@ -404,6 +404,19 @@ the values of parameters.  See the GLOBAL PARAMETERS section for more details.
785      the max connections limit is not exceeded for the modules sharing the lock
786      file.  The default is `/var/run/rsyncd.lock`.
787  
788 +0.  `checksum files`
789 +
790 +    This parameter tells rsync to make use of any cached checksum information
791 +    it finds in per-directory .rsyncsums files when the current transfer is
792 +    using the `--checksum` option.  The value can be set to either "lax",
793 +    "strict", or "none" -- see the client's `--sumfiles` option for what these
794 +    choices do.
795 +
796 +    Note also that the client's command-line option, `--sumfiles`, has no
797 +    effect on a daemon.  A daemon will only access checksum files if this
798 +    config option tells it to.  See also the `exclude` directive for a way to
799 +    hide the .rsyncsums files from the user.
800 +
801  0.  `read only`
802  
803      This parameter determines whether clients will be able to upload files or
804 diff --git a/support/rsyncsums b/support/rsyncsums
805 new file mode 100755
806 --- /dev/null
807 +++ b/support/rsyncsums
808 @@ -0,0 +1,201 @@
809 +#!/usr/bin/perl -w
810 +use strict;
811 +
812 +use Getopt::Long;
813 +use Cwd qw(abs_path cwd);
814 +use Digest::MD4;
815 +use Digest::MD5;
816 +
817 +our $SUMS_FILE = '.rsyncsums';
818 +
819 +&Getopt::Long::Configure('bundling');
820 +&usage if !&GetOptions(
821 +    'recurse|r' => \( my $recurse_opt ),
822 +    'mode|m=s' => \( my $cmp_mode = 'strict' ),
823 +    'check|c' => \( my $check_opt ),
824 +    'verbose|v+' => \( my $verbosity = 0 ),
825 +    'help|h' => \( my $help_opt ),
826 +);
827 +&usage if $help_opt || $cmp_mode !~ /^(lax|strict)$/;
828 +
829 +my $ignore_ctime_and_inode = $cmp_mode eq 'lax' ? 0 : 1;
830 +
831 +my $start_dir = cwd();
832 +
833 +my @dirs = @ARGV;
834 +@dirs = '.' unless @dirs;
835 +foreach (@dirs) {
836 +    $_ = abs_path($_);
837 +}
838 +
839 +$| = 1;
840 +
841 +my $exit_code = 0;
842 +
843 +my $md4 = Digest::MD4->new;
844 +my $md5 = Digest::MD5->new;
845 +
846 +while (@dirs) {
847 +    my $dir = shift @dirs;
848 +
849 +    if (!chdir($dir)) {
850 +       warn "Unable to chdir to $dir: $!\n";
851 +       next;
852 +    }
853 +    if (!opendir(DP, '.')) {
854 +       warn "Unable to opendir $dir: $!\n";
855 +       next;
856 +    }
857 +
858 +    my $reldir = $dir;
859 +    $reldir =~ s#^$start_dir(/|$)# $1 ? '' : '.' #eo;
860 +    if ($verbosity) {
861 +       print "$reldir ... ";
862 +       print "\n" if $check_opt;
863 +    }
864 +
865 +    my %cache;
866 +    my $f_cnt = 0;
867 +    if (open(FP, '<', $SUMS_FILE)) {
868 +       while (<FP>) {
869 +           chomp;
870 +           my($sum4, $sum5, $size, $mtime, $ctime, $inode, $fn) = split(' ', $_, 7);
871 +           $cache{$fn} = [ 0, $sum4, $sum5, $size, $mtime, $ctime & 0xFFFFFFFF, $inode & 0xFFFFFFFF ];
872 +           $f_cnt++;
873 +       }
874 +       close FP;
875 +    }
876 +
877 +    my @subdirs;
878 +    my $d_cnt = 0;
879 +    my $update_cnt = 0;
880 +    while (defined(my $fn = readdir(DP))) {
881 +       next if $fn =~ /^\.\.?$/ || $fn =~ /^\Q$SUMS_FILE\E$/o || -l $fn;
882 +       if (-d _) {
883 +           push(@subdirs, "$dir/$fn") unless $fn =~ /^(CVS|\.svn|\.git|\.bzr)$/;
884 +           next;
885 +       }
886 +       next unless -f _;
887 +
888 +       my($size,$mtime,$ctime,$inode) = (stat(_))[7,9,10,1];
889 +       $ctime &= 0xFFFFFFFF;
890 +       $inode &= 0xFFFFFFFF;
891 +       my $ref = $cache{$fn};
892 +       $d_cnt++;
893 +
894 +       if (!$check_opt) {
895 +           if (defined $ref) {
896 +               $$ref[0] = 1;
897 +               if ($$ref[3] == $size
898 +                && $$ref[4] == $mtime
899 +                && ($ignore_ctime_and_inode || ($$ref[5] == $ctime && $$ref[6] == $inode))
900 +                && $$ref[1] !~ /=/ && $$ref[2] !~ /=/) {
901 +                   next;
902 +               }
903 +           }
904 +           if (!$update_cnt++) {
905 +               print "UPDATING\n" if $verbosity;
906 +           }
907 +       }
908 +
909 +       if (!open(IN, $fn)) {
910 +           print STDERR "Unable to read $fn: $!\n";
911 +           if (defined $ref) {
912 +               delete $cache{$fn};
913 +               $f_cnt--;
914 +           }
915 +           next;
916 +       }
917 +
918 +       my($sum4, $sum5);
919 +       while (1) {
920 +           while (sysread(IN, $_, 64*1024)) {
921 +               $md4->add($_);
922 +               $md5->add($_);
923 +           }
924 +           $sum4 = $md4->hexdigest;
925 +           $sum5 = $md5->hexdigest;
926 +           print " $sum4 $sum5" if $verbosity > 2;
927 +           print " $fn" if $verbosity > 1;
928 +           my($size2,$mtime2,$ctime2,$inode2) = (stat(IN))[7,9,10,1];
929 +           $ctime2 &= 0xFFFFFFFF;
930 +           $inode2 &= 0xFFFFFFFF;
931 +           last if $size == $size2 && $mtime == $mtime2
932 +            && ($ignore_ctime_and_inode || ($ctime == $ctime2 && $inode == $inode2));
933 +           $size = $size2;
934 +           $mtime = $mtime2;
935 +           $ctime = $ctime2;
936 +           $inode = $inode2;
937 +           sysseek(IN, 0, 0);
938 +           print " REREADING\n" if $verbosity > 1;
939 +       }
940 +
941 +       close IN;
942 +
943 +       if ($check_opt) {
944 +           my $dif;
945 +           if (!defined $ref) {
946 +               $dif = 'MISSING';
947 +           } elsif ($sum4 ne $$ref[1] || $sum5 ne $$ref[2]) {
948 +               $dif = 'FAILED';
949 +           } else {
950 +               print " OK\n" if $verbosity > 1;
951 +               next;
952 +           }
953 +           if ($verbosity < 2) {
954 +               print $verbosity ? ' ' : "$reldir/";
955 +               print $fn;
956 +           }
957 +           print " $dif\n";
958 +           $exit_code = 1;
959 +       } else {
960 +           print "\n" if $verbosity > 1;
961 +           $cache{$fn} = [ 1, $sum4, $sum5, $size, $mtime, $ctime, $inode ];
962 +       }
963 +    }
964 +
965 +    closedir DP;
966 +
967 +    unshift(@dirs, sort @subdirs) if $recurse_opt;
968 +
969 +    if ($check_opt) {
970 +       ;
971 +    } elsif ($d_cnt == 0) {
972 +       if ($f_cnt) {
973 +           print "(removed $SUMS_FILE) " if $verbosity;
974 +           unlink($SUMS_FILE);
975 +       }
976 +       print "empty\n" if $verbosity;
977 +    } elsif ($update_cnt || $d_cnt != $f_cnt) {
978 +       print "UPDATING\n" if $verbosity && !$update_cnt;
979 +       open(FP, '>', $SUMS_FILE) or die "Unable to write $dir/$SUMS_FILE: $!\n";
980 +
981 +       foreach my $fn (sort keys %cache) {
982 +           my $ref = $cache{$fn};
983 +           my($found, $sum4, $sum5, $size, $mtime, $ctime, $inode) = @$ref;
984 +           next unless $found;
985 +           printf FP '%s %s %10d %10d %10d %10d %s' . "\n", $sum4, $sum5, $size, $mtime, $ctime, $inode, $fn;
986 +       }
987 +       close FP;
988 +    } else {
989 +       print "ok\n" if $verbosity;
990 +    }
991 +}
992 +
993 +exit $exit_code;
994 +
995 +sub usage
996 +{
997 +    die <<EOT;
998 +Usage: rsyncsums [OPTIONS] [DIRS]
999 +
1000 +Options:
1001 + -r, --recurse     Update $SUMS_FILE files in subdirectories too.
1002 + -m, --mode=MODE   Compare entries in either "lax" or "strict" mode.  Using
1003 +                   "lax" compares size and mtime, while "strict" additionally
1004 +                   compares ctime and inode.  Default:  strict.
1005 + -c, --check       Check if the checksums are right (doesn't update).
1006 + -v, --verbose     Mention what we're doing.  Repeat for more info.
1007 + -h, --help        Display this help message.
1008 +EOT
1009 +}