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