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