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