The patches for 3.3.0.
[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: d1a1fec1340254926e17f5d83f848f7574286a33
20 diff --git a/clientserver.c b/clientserver.c
21 --- a/clientserver.c
22 +++ b/clientserver.c
23 @@ -42,6 +42,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 @@ -902,6 +904,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 @@ -59,6 +61,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 @@ -70,6 +73,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 @@ -87,6 +91,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 @@ -129,7 +147,11 @@ static char tmp_sum[MAX_DIGEST_LEN];
99  static char empty_sum[MAX_DIGEST_LEN];
100  static int flist_count_offset; /* for --delete --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 @@ -343,6 +365,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, checksum_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 (protocol_version >= 30) {
225 +                       char *alt_sum = cp;
226 +                       if (*cp == '=')
227 +                               while (*++cp == '=') {}
228 +                       else
229 +                               while (isXDigit(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 < checksum_len*2; i++, cp++) {
239 +                               int x;
240 +                               if (isXDigit(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 (protocol_version < 30) {
260 +                       char *alt_sum = cp;
261 +                       if (*cp == '=')
262 +                               while (*++cp == '=') {}
263 +                       else
264 +                               while (isXDigit(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 @@ -1146,7 +1400,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 @@ -1292,9 +1546,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 @@ -1312,11 +1573,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 @@ -1401,8 +1659,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, checksum_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, checksum_len);
404 +       }
405  
406         if (unsort_ndx)
407                 F_NDX(file) = stats.num_dirs;
408 @@ -2584,7 +2848,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 @@ -2835,7 +3099,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 @@ -2886,7 +3150,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 @@ -2902,8 +3166,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 @@ -2925,7 +3189,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 @@ -51,6 +51,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 @@ -573,7 +574,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 @@ -582,7 +583,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), checksum_len) == 0;
485         }
486  
487 @@ -881,7 +885,7 @@ static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
488                         match_level = 1;
489                         /* FALL THROUGH */
490                 case 1:
491 -                       if (!unchanged_file(cmpbuf, file, &sxp->st))
492 +                       if (!unchanged_file(cmpbuf, file, &sxp->st, j+1))
493                                 continue;
494                         best_match = j;
495                         match_level = 2;
496 @@ -1188,7 +1192,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 @@ -1291,8 +1295,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 @@ -1300,7 +1305,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
518                 }
519                 parent_dirname = dn;
520  
521 -               if (need_fuzzy_dirlist && S_ISREG(file->mode)) {
522 +               if (need_new_dirscan && S_ISREG(file->mode)) {
523                         int i;
524                         strlcpy(fnamecmpbuf, dn, sizeof fnamecmpbuf);
525                         for (i = 0; i < fuzzy_basis; i++) {
526 @@ -1312,7 +1317,10 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
527                                         fuzzy_dirlist[i] = NULL;
528                                 }
529                         }
530 -                       need_fuzzy_dirlist = 0;
531 +                       if (checksum_files) {
532 +                               reset_checksum_cache();
533 +                       }
534 +                       need_new_dirscan = 0;
535                 }
536  
537                 statret = link_stat(fname, &sx.st, keep_dirlinks && is_dir);
538 @@ -1757,7 +1765,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx,
539                 ;
540         else if (fnamecmp_type == FNAMECMP_FUZZY)
541                 ;
542 -       else if (unchanged_file(fnamecmp, file, &sx.st)) {
543 +       else if (unchanged_file(fnamecmp, file, &sx.st, fnamecmp_type == FNAMECMP_FNAME ? 0 : -1)) {
544                 if (partialptr) {
545                         do_unlink(partialptr);
546                         handle_partial_dir(partialptr, PDIR_DELETE);
547 diff --git a/hlink.c b/hlink.c
548 --- a/hlink.c
549 +++ b/hlink.c
550 @@ -410,7 +410,7 @@ int hard_link_check(struct file_struct *file, int ndx, char *fname,
551                                 }
552                                 break;
553                         }
554 -                       if (!unchanged_file(cmpbuf, file, &alt_sx.st))
555 +                       if (!unchanged_file(cmpbuf, file, &alt_sx.st, j+1))
556                                 continue;
557                         statret = 1;
558                         if (unchanged_attrs(cmpbuf, file, &alt_sx))
559 diff --git a/itypes.h b/itypes.h
560 --- a/itypes.h
561 +++ b/itypes.h
562 @@ -23,6 +23,12 @@ isDigit(const char *ptr)
563  }
564  
565  static inline int
566 +isXDigit(const char *ptr)
567 +{
568 +       return isxdigit(*(unsigned char *)ptr);
569 +}
570 +
571 +static inline int
572  isPrint(const char *ptr)
573  {
574         return isprint(*(unsigned char *)ptr);
575 diff --git a/loadparm.c b/loadparm.c
576 --- a/loadparm.c
577 +++ b/loadparm.c
578 @@ -134,6 +134,7 @@ typedef struct {
579  /* NOTE: update this macro if the last char* variable changes! */
580  #define LOCAL_STRING_COUNT() (offsetof(local_vars, uid) / sizeof (char*) + 1)
581  
582 +       int checksum_files;
583         int max_connections;
584         int max_verbosity;
585         int syslog_facility;
586 @@ -208,6 +209,7 @@ static const all_vars Defaults = {
587   /* temp_dir; */               NULL,
588   /* uid; */                    NULL,
589  
590 + /* checksum_files; */         CSF_IGNORE_FILES,
591   /* max_connections; */                0,
592   /* max_verbosity; */          1,
593   /* syslog_facility; */                LOG_DAEMON,
594 @@ -310,6 +312,13 @@ static struct enum_list enum_facilities[] = {
595         { -1, NULL }
596  };
597  
598 +static struct enum_list enum_csum_modes[] = {
599 +       { CSF_IGNORE_FILES, "none" },
600 +       { CSF_LAX_MODE, "lax" },
601 +       { CSF_STRICT_MODE, "strict" },
602 +       { -1, NULL }
603 +};
604 +
605  static struct parm_struct parm_table[] =
606  {
607   {"address",           P_STRING, P_GLOBAL,&Vars.g.bind_address,        NULL,0},
608 @@ -321,6 +330,7 @@ static struct parm_struct parm_table[] =
609  
610   {"auth users",        P_STRING, P_LOCAL, &Vars.l.auth_users,          NULL,0},
611   {"charset",           P_STRING, P_LOCAL, &Vars.l.charset,             NULL,0},
612 + {"checksum files",    P_ENUM,   P_LOCAL, &Vars.l.checksum_files,      enum_csum_modes,0},
613   {"comment",           P_STRING, P_LOCAL, &Vars.l.comment,             NULL,0},
614   {"dont compress",     P_STRING, P_LOCAL, &Vars.l.dont_compress,       NULL,0},
615   {"exclude from",      P_STRING, P_LOCAL, &Vars.l.exclude_from,        NULL,0},
616 @@ -477,6 +487,7 @@ FN_LOCAL_STRING(lp_secrets_file, secrets_file)
617  FN_LOCAL_STRING(lp_temp_dir, temp_dir)
618  FN_LOCAL_STRING(lp_uid, uid)
619  
620 +FN_LOCAL_INTEGER(lp_checksum_files, checksum_files)
621  FN_LOCAL_INTEGER(lp_max_connections, max_connections)
622  FN_LOCAL_INTEGER(lp_max_verbosity, max_verbosity)
623  FN_LOCAL_INTEGER(lp_syslog_facility, syslog_facility)
624 diff --git a/options.c b/options.c
625 --- a/options.c
626 +++ b/options.c
627 @@ -115,6 +115,7 @@ size_t bwlimit_writemax = 0;
628  int ignore_existing = 0;
629  int ignore_non_existing = 0;
630  int need_messages_from_generator = 0;
631 +int checksum_files = CSF_IGNORE_FILES;
632  int max_delete = INT_MIN;
633  OFF_T max_size = -1;
634  OFF_T min_size = -1;
635 @@ -672,6 +673,7 @@ void usage(enum logcode F)
636    rprintf(F," -q, --quiet                 suppress non-error messages\n");
637    rprintf(F,"     --no-motd               suppress daemon-mode MOTD (see manpage caveat)\n");
638    rprintf(F," -c, --checksum              skip based on checksum, not mod-time & size\n");
639 +  rprintf(F,"     --sumfiles=MODE         use .rsyncsums to speedup --checksum mode\n");
640    rprintf(F," -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)\n");
641    rprintf(F,"     --no-OPTION             turn off an implied OPTION (e.g. --no-D)\n");
642    rprintf(F," -r, --recursive             recurse into directories\n");
643 @@ -819,7 +821,7 @@ enum {OPT_VERSION = 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_SERVER, OPT_REFUSED_BASE = 9000};
651  
652 @@ -960,6 +962,7 @@ static struct poptOption long_options[] = {
653    {"checksum",        'c', POPT_ARG_VAL,    &always_checksum, 1, 0, 0 },
654    {"no-checksum",      0,  POPT_ARG_VAL,    &always_checksum, 0, 0, 0 },
655    {"no-c",             0,  POPT_ARG_VAL,    &always_checksum, 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 @@ -1676,6 +1679,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 @@ -1953,6 +1973,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 > MAX_BLOCK_SIZE) {
692                 snprintf(err_buf, sizeof err_buf,
693                          "--block-size=%lu is too large (max: %u)\n", block_size, MAX_BLOCK_SIZE);
694 diff --git a/rsync.h b/rsync.h
695 --- a/rsync.h
696 +++ b/rsync.h
697 @@ -772,6 +772,10 @@ extern int xattrs_ndx;
698  #define F_SUM(f) ((char*)OPT_EXTRA(f, START_BUMP(f) + HLINK_BUMP(f) \
699                                     + SUM_EXTRA_CNT - 1))
700  
701 +/* These are only valid on an entry read from a checksum file. */
702 +#define F_CTIME(f) OPT_EXTRA(f, LEN64_BUMP(f) + SUM_EXTRA_CNT)->unum
703 +#define F_INODE(f) OPT_EXTRA(f, LEN64_BUMP(f) + SUM_EXTRA_CNT + 1)->unum
704 +
705  /* Some utility defines: */
706  #define F_IS_ACTIVE(f) (f)->basename[0]
707  #define F_IS_HLINKED(f) ((f)->flags & FLAG_HLINKED)
708 @@ -969,6 +973,13 @@ typedef struct {
709         char fname[1]; /* has variable size */
710  } relnamecache;
711  
712 +#define CSF_ENABLE (1<<1)
713 +#define CSF_LAX (1<<2)
714 +
715 +#define CSF_IGNORE_FILES 0
716 +#define CSF_LAX_MODE (CSF_ENABLE|CSF_LAX)
717 +#define CSF_STRICT_MODE (CSF_ENABLE)
718 +
719  #include "byteorder.h"
720  #include "lib/mdigest.h"
721  #include "lib/wildmatch.h"
722 diff --git a/rsync.yo b/rsync.yo
723 --- a/rsync.yo
724 +++ b/rsync.yo
725 @@ -340,6 +340,7 @@ to the detailed description below for a complete description.  verb(
726   -q, --quiet                 suppress non-error messages
727       --no-motd               suppress daemon-mode MOTD (see caveat)
728   -c, --checksum              skip based on checksum, not mod-time & size
729 +     --sumfiles=MODE         use .rsyncsums to speedup --checksum mode
730   -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
731       --no-OPTION             turn off an implied OPTION (e.g. --no-D)
732   -r, --recursive             recurse into directories
733 @@ -630,9 +631,9 @@ uses a "quick check" that (by default) checks if each file's size and time
734  of last modification match between the sender and receiver.  This option
735  changes this to compare a 128-bit checksum for each file that has a
736  matching size.  Generating the checksums means that both sides will expend
737 -a lot of disk I/O reading all the data in the files in the transfer (and
738 -this is prior to any reading that will be done to transfer changed files),
739 -so this can slow things down significantly.
740 +a lot of disk I/O reading the data in all the files in the transfer, so
741 +this can slow things down significantly (and this is prior to any reading
742 +that will be done to transfer the files that have changed).
743  
744  The sending side generates its checksums while it is doing the file-system
745  scan that builds the list of the available files.  The receiver generates
746 @@ -640,6 +641,8 @@ its checksums when it is scanning for changed files, and will checksum any
747  file that has the same size as the corresponding sender's file:  files with
748  either a changed size or a changed checksum are selected for transfer.
749  
750 +See also the bf(--sumfiles) option for a way to use cached checksum data.
751 +
752  Note that rsync always verifies that each em(transferred) file was
753  correctly reconstructed on the receiving side by checking a whole-file
754  checksum that is generated as the file is transferred, but that
755 @@ -649,6 +652,36 @@ option's before-the-transfer "Does this file need to be updated?" check.
756  For protocol 30 and beyond (first supported in 3.0.0), the checksum used is
757  MD5.  For older protocols, the checksum used is MD4.
758  
759 +dit(bf(--sumfiles=MODE)) This option tells rsync to make use of any cached
760 +checksum information it finds in per-directory .rsyncsums files when the
761 +current transfer is using the bf(--checksum) option.  If the checksum data
762 +is up-to-date, it is used instead of recomputing it, saving both disk I/O
763 +and CPU time.  If the checksum data is missing or outdated, the checksum is
764 +computed just as it would be if bf(--sumfiles) was not specified.
765 +
766 +The MODE value is either "lax", for relaxed checking (which compares size
767 +and mtime), "strict" (which also compares ctime and inode), or "none" to
768 +ignore any .rsyncsums files ("none" is the default).  Rsync does not create
769 +or update these files, but there is a perl script in the support directory
770 +named "rsyncsums" that can be used for that.
771 +
772 +This option has no effect unless bf(--checksum, -c) was also specified.  It
773 +also only affects the current side of the transfer, so if you want the
774 +remote side to parse its own .rsyncsums files, specify the option via the
775 +bf(--rsync-path) option (e.g. "--rsync-path="rsync --sumfiles=lax").
776 +
777 +To avoid transferring the system's checksum files, you can use an exclude
778 +(e.g. bf(--exclude=.rsyncsums)).  To make this easier to type, you can use
779 +a popt alias.  For instance, adding the following line in your ~/.popt file
780 +defines a bf(--cc) option that enables lax checksum files and excludes the
781 +checksum files:
782 +
783 +verb(  rsync alias --cc -c --sumfiles=lax --exclude=.rsyncsums)
784 +
785 +An rsync daemon does not allow the client to control this setting, so see
786 +the "checksum files" daemon parameter for information on how to make a
787 +daemon use cached checksum data.
788 +
789  dit(bf(-a, --archive)) This is equivalent to bf(-rlptgoD). It is a quick
790  way of saying you want recursion and want to preserve almost
791  everything (with -H being a notable omission).
792 diff --git a/rsyncd.conf.yo b/rsyncd.conf.yo
793 --- a/rsyncd.conf.yo
794 +++ b/rsyncd.conf.yo
795 @@ -334,6 +334,17 @@ locking on this file to ensure that the max connections limit is not
796  exceeded for the modules sharing the lock file.
797  The default is tt(/var/run/rsyncd.lock).
798  
799 +dit(bf(checksum files)) This parameter tells rsync to make use of any cached
800 +checksum information it finds in per-directory .rsyncsums files when the
801 +current transfer is using the bf(--checksum) option.  The value can be set
802 +to either "lax", "strict", or "none" -- see the client's bf(--sumfiles)
803 +option for what these choices do.
804 +
805 +Note also that the client's command-line option, bf(--sumfiles), has no
806 +effect on a daemon.  A daemon will only access checksum files if this
807 +config option tells it to.  See also the bf(exclude) directive for a way
808 +to hide the .rsyncsums files from the user.
809 +
810  dit(bf(read only)) This parameter determines whether clients
811  will be able to upload files or not. If "read only" is true then any
812  attempted uploads will fail. If "read only" is false then uploads will
813 diff --git a/support/rsyncsums b/support/rsyncsums
814 new file mode 100755
815 --- /dev/null
816 +++ b/support/rsyncsums
817 @@ -0,0 +1,201 @@
818 +#!/usr/bin/perl -w
819 +use strict;
820 +
821 +use Getopt::Long;
822 +use Cwd qw(abs_path cwd);
823 +use Digest::MD4;
824 +use Digest::MD5;
825 +
826 +our $SUMS_FILE = '.rsyncsums';
827 +
828 +&Getopt::Long::Configure('bundling');
829 +&usage if !&GetOptions(
830 +    'recurse|r' => \( my $recurse_opt ),
831 +    'mode|m=s' => \( my $cmp_mode = 'strict' ),
832 +    'check|c' => \( my $check_opt ),
833 +    'verbose|v+' => \( my $verbosity = 0 ),
834 +    'help|h' => \( my $help_opt ),
835 +);
836 +&usage if $help_opt || $cmp_mode !~ /^(lax|strict)$/;
837 +
838 +my $ignore_ctime_and_inode = $cmp_mode eq 'lax' ? 0 : 1;
839 +
840 +my $start_dir = cwd();
841 +
842 +my @dirs = @ARGV;
843 +@dirs = '.' unless @dirs;
844 +foreach (@dirs) {
845 +    $_ = abs_path($_);
846 +}
847 +
848 +$| = 1;
849 +
850 +my $exit_code = 0;
851 +
852 +my $md4 = Digest::MD4->new;
853 +my $md5 = Digest::MD5->new;
854 +
855 +while (@dirs) {
856 +    my $dir = shift @dirs;
857 +
858 +    if (!chdir($dir)) {
859 +       warn "Unable to chdir to $dir: $!\n";
860 +       next;
861 +    }
862 +    if (!opendir(DP, '.')) {
863 +       warn "Unable to opendir $dir: $!\n";
864 +       next;
865 +    }
866 +
867 +    my $reldir = $dir;
868 +    $reldir =~ s#^$start_dir(/|$)# $1 ? '' : '.' #eo;
869 +    if ($verbosity) {
870 +       print "$reldir ... ";
871 +       print "\n" if $check_opt;
872 +    }
873 +
874 +    my %cache;
875 +    my $f_cnt = 0;
876 +    if (open(FP, '<', $SUMS_FILE)) {
877 +       while (<FP>) {
878 +           chomp;
879 +           my($sum4, $sum5, $size, $mtime, $ctime, $inode, $fn) = split(' ', $_, 7);
880 +           $cache{$fn} = [ 0, $sum4, $sum5, $size, $mtime, $ctime & 0xFFFFFFFF, $inode & 0xFFFFFFFF ];
881 +           $f_cnt++;
882 +       }
883 +       close FP;
884 +    }
885 +
886 +    my @subdirs;
887 +    my $d_cnt = 0;
888 +    my $update_cnt = 0;
889 +    while (defined(my $fn = readdir(DP))) {
890 +       next if $fn =~ /^\.\.?$/ || $fn =~ /^\Q$SUMS_FILE\E$/o || -l $fn;
891 +       if (-d _) {
892 +           push(@subdirs, "$dir/$fn") unless $fn =~ /^(CVS|\.svn|\.git|\.bzr)$/;
893 +           next;
894 +       }
895 +       next unless -f _;
896 +
897 +       my($size,$mtime,$ctime,$inode) = (stat(_))[7,9,10,1];
898 +       $ctime &= 0xFFFFFFFF;
899 +       $inode &= 0xFFFFFFFF;
900 +       my $ref = $cache{$fn};
901 +       $d_cnt++;
902 +
903 +       if (!$check_opt) {
904 +           if (defined $ref) {
905 +               $$ref[0] = 1;
906 +               if ($$ref[3] == $size
907 +                && $$ref[4] == $mtime
908 +                && ($ignore_ctime_and_inode || ($$ref[5] == $ctime && $$ref[6] == $inode))
909 +                && $$ref[1] !~ /=/ && $$ref[2] !~ /=/) {
910 +                   next;
911 +               }
912 +           }
913 +           if (!$update_cnt++) {
914 +               print "UPDATING\n" if $verbosity;
915 +           }
916 +       }
917 +
918 +       if (!open(IN, $fn)) {
919 +           print STDERR "Unable to read $fn: $!\n";
920 +           if (defined $ref) {
921 +               delete $cache{$fn};
922 +               $f_cnt--;
923 +           }
924 +           next;
925 +       }
926 +
927 +       my($sum4, $sum5);
928 +       while (1) {
929 +           while (sysread(IN, $_, 64*1024)) {
930 +               $md4->add($_);
931 +               $md5->add($_);
932 +           }
933 +           $sum4 = $md4->hexdigest;
934 +           $sum5 = $md5->hexdigest;
935 +           print " $sum4 $sum5" if $verbosity > 2;
936 +           print " $fn" if $verbosity > 1;
937 +           my($size2,$mtime2,$ctime2,$inode2) = (stat(IN))[7,9,10,1];
938 +           $ctime2 &= 0xFFFFFFFF;
939 +           $inode2 &= 0xFFFFFFFF;
940 +           last if $size == $size2 && $mtime == $mtime2
941 +            && ($ignore_ctime_and_inode || ($ctime == $ctime2 && $inode == $inode2));
942 +           $size = $size2;
943 +           $mtime = $mtime2;
944 +           $ctime = $ctime2;
945 +           $inode = $inode2;
946 +           sysseek(IN, 0, 0);
947 +           print " REREADING\n" if $verbosity > 1;
948 +       }
949 +
950 +       close IN;
951 +
952 +       if ($check_opt) {
953 +           my $dif;
954 +           if (!defined $ref) {
955 +               $dif = 'MISSING';
956 +           } elsif ($sum4 ne $$ref[1] || $sum5 ne $$ref[2]) {
957 +               $dif = 'FAILED';
958 +           } else {
959 +               print " OK\n" if $verbosity > 1;
960 +               next;
961 +           }
962 +           if ($verbosity < 2) {
963 +               print $verbosity ? ' ' : "$reldir/";
964 +               print $fn;
965 +           }
966 +           print " $dif\n";
967 +           $exit_code = 1;
968 +       } else {
969 +           print "\n" if $verbosity > 1;
970 +           $cache{$fn} = [ 1, $sum4, $sum5, $size, $mtime, $ctime, $inode ];
971 +       }
972 +    }
973 +
974 +    closedir DP;
975 +
976 +    unshift(@dirs, sort @subdirs) if $recurse_opt;
977 +
978 +    if ($check_opt) {
979 +       ;
980 +    } elsif ($d_cnt == 0) {
981 +       if ($f_cnt) {
982 +           print "(removed $SUMS_FILE) " if $verbosity;
983 +           unlink($SUMS_FILE);
984 +       }
985 +       print "empty\n" if $verbosity;
986 +    } elsif ($update_cnt || $d_cnt != $f_cnt) {
987 +       print "UPDATING\n" if $verbosity && !$update_cnt;
988 +       open(FP, '>', $SUMS_FILE) or die "Unable to write $dir/$SUMS_FILE: $!\n";
989 +
990 +       foreach my $fn (sort keys %cache) {
991 +           my $ref = $cache{$fn};
992 +           my($found, $sum4, $sum5, $size, $mtime, $ctime, $inode) = @$ref;
993 +           next unless $found;
994 +           printf FP '%s %s %10d %10d %10d %10d %s' . "\n", $sum4, $sum5, $size, $mtime, $ctime, $inode, $fn;
995 +       }
996 +       close FP;
997 +    } else {
998 +       print "ok\n" if $verbosity;
999 +    }
1000 +}
1001 +
1002 +exit $exit_code;
1003 +
1004 +sub usage
1005 +{
1006 +    die <<EOT;
1007 +Usage: rsyncsums [OPTIONS] [DIRS]
1008 +
1009 +Options:
1010 + -r, --recurse     Update $SUMS_FILE files in subdirectories too.
1011 + -m, --mode=MODE   Compare entries in either "lax" or "strict" mode.  Using
1012 +                   "lax" compares size and mtime, while "strict" additionally
1013 +                   compares ctime and inode.  Default:  strict.
1014 + -c, --check       Check if the checksums are right (doesn't update).
1015 + -v, --verbose     Mention what we're doing.  Repeat for more info.
1016 + -h, --help        Display this help message.
1017 +EOT
1018 +}