- Call maybe_send_keepalive() if timeouts are enabled.
[rsync/rsync.git] / generator.c
1 /* -*- c-file-style: "linux" -*-
2
3    rsync -- fast file replication program
4
5    Copyright (C) 1996-2000 by Andrew Tridgell
6    Copyright (C) Paul Mackerras 1996
7    Copyright (C) 2002 by Martin Pool <mbp@samba.org>
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "rsync.h"
25
26 extern int verbose;
27 extern int dry_run;
28 extern int log_format_has_i;
29 extern int log_format_has_o_or_i;
30 extern int daemon_log_format_has_i;
31 extern int am_root;
32 extern int am_server;
33 extern int am_daemon;
34 extern int relative_paths;
35 extern int keep_dirlinks;
36 extern int preserve_links;
37 extern int preserve_devices;
38 extern int preserve_hard_links;
39 extern int preserve_perms;
40 extern int preserve_uid;
41 extern int preserve_gid;
42 extern int preserve_times;
43 extern int omit_dir_times;
44 extern int delete_during;
45 extern int remove_sent_files;
46 extern int update_only;
47 extern int opt_ignore_existing;
48 extern int inplace;
49 extern int make_backups;
50 extern int csum_length;
51 extern int ignore_times;
52 extern int size_only;
53 extern OFF_T max_size;
54 extern int io_timeout;
55 extern int ignore_timeout;
56 extern int protocol_version;
57 extern int fuzzy_basis;
58 extern int always_checksum;
59 extern char *partial_dir;
60 extern char *basis_dir[];
61 extern int compare_dest;
62 extern int link_dest;
63 extern int whole_file;
64 extern int local_server;
65 extern int list_only;
66 extern int read_batch;
67 extern int only_existing;
68 extern int orig_umask;
69 extern int safe_symlinks;
70 extern long block_size; /* "long" because popt can't set an int32. */
71 extern struct stats stats;
72
73 extern struct filter_list_struct server_filter_list;
74
75 static int unchanged_attrs(struct file_struct *file, STRUCT_STAT *st)
76 {
77         if (preserve_perms
78          && (st->st_mode & CHMOD_BITS) != (file->mode & CHMOD_BITS))
79                 return 0;
80
81         if (am_root && preserve_uid && st->st_uid != file->uid)
82                 return 0;
83
84         if (preserve_gid && file->gid != GID_NONE && st->st_gid != file->gid)
85                 return 0;
86
87         return 1;
88 }
89
90
91 #define SID_UPDATING              ITEM_UPDATING
92 #define SID_REPORT_CHECKSUM       ITEM_REPORT_CHECKSUM
93 #define SID_USING_ALT_BASIS       ITEM_USING_ALT_BASIS
94 /* This flag doesn't get sent, so it must be outside 0xffff. */
95 #define SID_NO_DEST_AND_NO_UPDATE (1<<16)
96
97 static void itemize(struct file_struct *file, int statret, STRUCT_STAT *st,
98                     int32 sflags, int f_out, int ndx)
99 {
100         int iflags = sflags & 0xffff;
101
102         if (statret >= 0) {
103                 if (S_ISREG(file->mode) && file->length != st->st_size)
104                         iflags |= ITEM_REPORT_SIZE;
105                 if (!(sflags & SID_NO_DEST_AND_NO_UPDATE)) {
106                         int keep_time = !preserve_times ? 0
107                             : S_ISDIR(file->mode) ? !omit_dir_times
108                             : !S_ISLNK(file->mode);
109
110                         if ((iflags & ITEM_UPDATING && !keep_time)
111                             || (keep_time && file->modtime != st->st_mtime))
112                                 iflags |= ITEM_REPORT_TIME;
113                         if (preserve_perms && file->mode != st->st_mode)
114                                 iflags |= ITEM_REPORT_PERMS;
115                         if (preserve_uid && am_root && file->uid != st->st_uid)
116                                 iflags |= ITEM_REPORT_OWNER;
117                         if (preserve_gid && file->gid != GID_NONE
118                             && st->st_gid != file->gid)
119                                 iflags |= ITEM_REPORT_GROUP;
120                 }
121         } else
122                 iflags |= ITEM_IS_NEW | ITEM_UPDATING;
123
124         if ((iflags || verbose > 1) && !read_batch) {
125                 if (protocol_version >= 29) {
126                         if (ndx >= 0)
127                                 write_int(f_out, ndx);
128                         write_shortint(f_out, iflags);
129                 } else if (ndx >= 0)
130                         log_recv(file, &stats, iflags);
131         }
132 }
133
134
135 /* Perform our quick-check heuristic for determining if a file is unchanged. */
136 static int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
137 {
138         if (st->st_size != file->length)
139                 return 0;
140
141         /* if always checksum is set then we use the checksum instead
142            of the file time to determine whether to sync */
143         if (always_checksum && S_ISREG(st->st_mode)) {
144                 char sum[MD4_SUM_LENGTH];
145                 file_checksum(fn, sum, st->st_size);
146                 return memcmp(sum, file->u.sum, protocol_version < 21 ? 2
147                                                         : MD4_SUM_LENGTH) == 0;
148         }
149
150         if (size_only)
151                 return 1;
152
153         if (ignore_times)
154                 return 0;
155
156         return cmp_modtime(st->st_mtime, file->modtime) == 0;
157 }
158
159
160 /*
161  * set (initialize) the size entries in the per-file sum_struct
162  * calculating dynamic block and checksum sizes.
163  *
164  * This is only called from generate_and_send_sums() but is a separate
165  * function to encapsulate the logic.
166  *
167  * The block size is a rounded square root of file length.
168  *
169  * The checksum size is determined according to:
170  *     blocksum_bits = BLOCKSUM_EXP + 2*log2(file_len) - log2(block_len)
171  * provided by Donovan Baarda which gives a probability of rsync
172  * algorithm corrupting data and falling back using the whole md4
173  * checksums.
174  *
175  * This might be made one of several selectable heuristics.
176  */
177 static void sum_sizes_sqroot(struct sum_struct *sum, int64 len)
178 {
179         int32 blength;
180         int s2length;
181
182         if (block_size)
183                 blength = block_size;
184         else if (len <= BLOCK_SIZE * BLOCK_SIZE)
185                 blength = BLOCK_SIZE;
186         else {
187                 int32 c;
188                 int64 l;
189                 int cnt;
190                 for (c = 1, l = len, cnt = 0; l >>= 2; c <<= 1, cnt++) {}
191                 if (cnt >= 31 || c >= MAX_BLOCK_SIZE)
192                         blength = MAX_BLOCK_SIZE;
193                 else {
194                     blength = 0;
195                     do {
196                             blength |= c;
197                             if (len < (int64)blength * blength)
198                                     blength &= ~c;
199                             c >>= 1;
200                     } while (c >= 8);   /* round to multiple of 8 */
201                     blength = MAX(blength, BLOCK_SIZE);
202                 }
203         }
204
205         if (protocol_version < 27) {
206                 s2length = csum_length;
207         } else if (csum_length == SUM_LENGTH) {
208                 s2length = SUM_LENGTH;
209         } else {
210                 int32 c;
211                 int64 l;
212                 int b = BLOCKSUM_BIAS;
213                 for (l = len; l >>= 1; b += 2) {}
214                 for (c = blength; c >>= 1 && b; b--) {}
215                 /* add a bit, subtract rollsum, round up. */
216                 s2length = (b + 1 - 32 + 7) / 8; /* --optimize in compiler-- */
217                 s2length = MAX(s2length, csum_length);
218                 s2length = MIN(s2length, SUM_LENGTH);
219         }
220
221         sum->flength    = len;
222         sum->blength    = blength;
223         sum->s2length   = s2length;
224         sum->count      = (len + (blength - 1)) / blength;
225         sum->remainder  = (len % blength);
226
227         if (sum->count && verbose > 2) {
228                 rprintf(FINFO,
229                         "count=%.0f rem=%ld blength=%ld s2length=%d flength=%.0f\n",
230                         (double)sum->count, (long)sum->remainder, (long)sum->blength,
231                         sum->s2length, (double)sum->flength);
232         }
233 }
234
235
236 /*
237  * Generate and send a stream of signatures/checksums that describe a buffer
238  *
239  * Generate approximately one checksum every block_len bytes.
240  */
241 static void generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy)
242 {
243         int32 i;
244         struct map_struct *mapbuf;
245         struct sum_struct sum;
246         OFF_T offset = 0;
247
248         sum_sizes_sqroot(&sum, len);
249
250         if (len > 0)
251                 mapbuf = map_file(fd, len, MAX_MAP_SIZE, sum.blength);
252         else
253                 mapbuf = NULL;
254
255         write_sum_head(f_out, &sum);
256
257         for (i = 0; i < sum.count; i++) {
258                 int32 n1 = (int32)MIN(len, (OFF_T)sum.blength);
259                 char *map = map_ptr(mapbuf, offset, n1);
260                 uint32 sum1 = get_checksum1(map, n1);
261                 char sum2[SUM_LENGTH];
262
263                 if (f_copy >= 0)
264                         full_write(f_copy, map, n1);
265
266                 get_checksum2(map, n1, sum2);
267
268                 if (verbose > 3) {
269                         rprintf(FINFO,
270                                 "chunk[%.0f] offset=%.0f len=%ld sum1=%08lx\n",
271                                 (double)i, (double)offset, (long)n1,
272                                 (unsigned long)sum1);
273                 }
274                 write_int(f_out, sum1);
275                 write_buf(f_out, sum2, sum.s2length);
276                 len -= n1;
277                 offset += n1;
278         }
279
280         if (mapbuf)
281                 unmap_file(mapbuf);
282 }
283
284
285 /* Try to find a filename in the same dir as "fname" with a similar name. */
286 static int find_fuzzy(struct file_struct *file, struct file_list *dirlist)
287 {
288         int fname_len, fname_suf_len;
289         const char *fname_suf, *fname = file->basename;
290         uint32 lowest_dist = 0x7FFFFFFF;
291         int j, lowest_j = -1;
292
293         fname_len = strlen(fname);
294         fname_suf = find_filename_suffix(fname, fname_len, &fname_suf_len);
295
296         for (j = 0; j < dirlist->count; j++) {
297                 struct file_struct *fp = dirlist->files[j];
298                 const char *suf, *name;
299                 int len, suf_len;
300                 uint32 dist;
301
302                 if (!S_ISREG(fp->mode) || !fp->length
303                     || fp->flags & FLAG_NO_FUZZY)
304                         continue;
305
306                 name = fp->basename;
307
308                 if (fp->length == file->length
309                     && fp->modtime == file->modtime) {
310                         if (verbose > 4) {
311                                 rprintf(FINFO,
312                                         "fuzzy size/modtime match for %s\n",
313                                         name);
314                         }
315                         return j;
316                 }
317
318                 len = strlen(name);
319                 suf = find_filename_suffix(name, len, &suf_len);
320
321                 dist = fuzzy_distance(name, len, fname, fname_len);
322                 /* Add some extra weight to how well the suffixes match. */
323                 dist += fuzzy_distance(suf, suf_len, fname_suf, fname_suf_len)
324                       * 10;
325                 if (verbose > 4) {
326                         rprintf(FINFO, "fuzzy distance for %s = %d.%05d\n",
327                                 name, (int)(dist>>16), (int)(dist&0xFFFF));
328                 }
329                 if (dist <= lowest_dist) {
330                         lowest_dist = dist;
331                         lowest_j = j;
332                 }
333         }
334
335         return lowest_j;
336 }
337
338
339 /* Acts on flist->file's ndx'th item, whose name is fname.  If a directory,
340  * make sure it exists, and has the right permissions/timestamp info.  For
341  * all other non-regular files (symlinks, etc.) we create them here.  For
342  * regular files that have changed, we try to find a basis file and then
343  * start sending checksums.
344  *
345  * Note that f_out is set to -1 when doing final directory-permission and
346  * modification-time repair. */
347 static void recv_generator(char *fname, struct file_list *flist,
348                            struct file_struct *file, int ndx,
349                            int f_out, int f_out_name)
350 {
351         static int missing_below = -1, excluded_below = -1;
352         static char *fuzzy_dirname = NULL;
353         static struct file_list *fuzzy_dirlist = NULL;
354         struct file_struct *fuzzy_file = NULL;
355         int fd = -1, f_copy = -1;
356         STRUCT_STAT st, partial_st;
357         struct file_struct *back_file = NULL;
358         int statret, stat_errno;
359         char *fnamecmp, *partialptr, *backupptr = NULL;
360         char fnamecmpbuf[MAXPATHLEN];
361         int itemizing, maybe_PERMS_REPORT;
362         uchar fnamecmp_type;
363         enum logcode code;
364
365         if (list_only)
366                 return;
367
368         if (protocol_version >= 29) {
369                 itemizing = 1;
370                 code = daemon_log_format_has_i ? 0 : FLOG;
371                 maybe_PERMS_REPORT = log_format_has_i ? 0 : PERMS_REPORT;
372         } else if (am_daemon) {
373                 itemizing = daemon_log_format_has_i && !dry_run;
374                 code = itemizing || dry_run ? FCLIENT : FINFO;
375                 maybe_PERMS_REPORT = PERMS_REPORT;
376         } else if (!am_server) {
377                 itemizing = log_format_has_i;
378                 code = itemizing ? 0 : FINFO;
379                 maybe_PERMS_REPORT = log_format_has_i ? 0 : PERMS_REPORT;
380         } else {
381                 itemizing = 0;
382                 code = FINFO;
383                 maybe_PERMS_REPORT = PERMS_REPORT;
384         }
385
386         if (!fname) {
387                 if (fuzzy_dirlist) {
388                         flist_free(fuzzy_dirlist);
389                         fuzzy_dirlist = NULL;
390                         fuzzy_dirname = NULL;
391                 }
392                 if (missing_below >= 0) {
393                         dry_run--;
394                         missing_below = -1;
395                 }
396                 return;
397         }
398
399         if (verbose > 2) {
400                 rprintf(FINFO, "recv_generator(%s,%d)\n",
401                         safe_fname(fname), ndx);
402         }
403
404         if (server_filter_list.head) {
405                 if (excluded_below >= 0) {
406                         if (file->dir.depth > excluded_below)
407                                 goto skipping;
408                         excluded_below = -1;
409                 }
410                 if (check_filter(&server_filter_list, fname,
411                                  S_ISDIR(file->mode)) < 0) {
412                         if (S_ISDIR(file->mode))
413                                 excluded_below = file->dir.depth;
414                     skipping:
415                         if (verbose) {
416                                 rprintf(FINFO,
417                                         "skipping server-excluded file \"%s\"\n",
418                                         safe_fname(fname));
419                         }
420                         return;
421                 }
422         }
423
424         if (missing_below >= 0 && file->dir.depth <= missing_below) {
425                 dry_run--;
426                 missing_below = -1;
427         }
428         if (dry_run > 1) {
429                 statret = -1;
430                 stat_errno = ENOENT;
431         } else {
432                 if (fuzzy_basis && S_ISREG(file->mode)) {
433                         char *dn = file->dirname ? file->dirname : ".";
434                         /* Yes, identical dirnames are guaranteed to have
435                          * identical pointers at this point. */
436                         if (fuzzy_dirname != dn) {
437                                 if (fuzzy_dirlist)
438                                         flist_free(fuzzy_dirlist);
439                                 fuzzy_dirname = dn;
440                                 fuzzy_dirlist = get_dirlist(fuzzy_dirname, 1);
441                         }
442                 }
443
444                 statret = link_stat(fname, &st,
445                                     keep_dirlinks && S_ISDIR(file->mode));
446                 stat_errno = errno;
447         }
448
449         if (only_existing && statret == -1 && stat_errno == ENOENT) {
450                 /* we only want to update existing files */
451                 if (verbose > 1) {
452                         rprintf(FINFO, "not creating new file \"%s\"\n",
453                                 safe_fname(fname));
454                 }
455                 return;
456         }
457
458         if (statret == 0 && !preserve_perms
459             && S_ISDIR(st.st_mode) == S_ISDIR(file->mode)) {
460                 /* if the file exists already and we aren't perserving
461                  * permissions then act as though the remote end sent
462                  * us the file permissions we already have */
463                 file->mode = (file->mode & ~CHMOD_BITS)
464                            | (st.st_mode & CHMOD_BITS);
465         }
466
467         if (S_ISDIR(file->mode)) {
468                 /* The file to be received is a directory, so we need
469                  * to prepare appropriately.  If there is already a
470                  * file of that name and it is *not* a directory, then
471                  * we need to delete it.  If it doesn't exist, then
472                  * (perhaps recursively) create it. */
473                 if (statret == 0 && !S_ISDIR(st.st_mode)) {
474                         delete_file(fname, st.st_mode, DEL_TERSE);
475                         statret = -1;
476                 }
477                 if (dry_run && statret != 0 && missing_below < 0) {
478                         missing_below = file->dir.depth;
479                         dry_run++;
480                 }
481                 if (itemizing && f_out != -1)
482                         itemize(file, statret, &st, 0, f_out, ndx);
483                 if (statret != 0 && do_mkdir(fname,file->mode) != 0 && errno != EEXIST) {
484                         if (!relative_paths || errno != ENOENT
485                             || create_directory_path(fname, orig_umask) < 0
486                             || do_mkdir(fname, file->mode) < 0) {
487                                 rsyserr(FERROR, errno,
488                                         "recv_generator: mkdir %s failed",
489                                         full_fname(fname));
490                         }
491                 }
492                 if (set_perms(fname, file, statret ? NULL : &st, 0)
493                     && verbose && code && f_out != -1)
494                         rprintf(code, "%s/\n", safe_fname(fname));
495                 if (delete_during && f_out != -1 && csum_length != SUM_LENGTH
496                     && (file->flags & FLAG_DEL_HERE))
497                         delete_in_dir(flist, fname, file);
498                 return;
499         }
500
501         if (max_size && file->length > max_size) {
502                 if (verbose > 1) {
503                         rprintf(FINFO, "%s is over max-size\n",
504                                 safe_fname(fname));
505                 }
506                 return;
507         }
508
509         if (preserve_links && S_ISLNK(file->mode)) {
510 #ifdef SUPPORT_LINKS
511                 if (safe_symlinks && unsafe_symlink(file->u.link, fname)) {
512                         if (verbose) {
513                                 rprintf(FINFO,
514                                         "ignoring unsafe symlink %s -> \"%s\"\n",
515                                         full_fname(fname),
516                                         safe_fname(file->u.link));
517                         }
518                         return;
519                 }
520                 if (statret == 0) {
521                         char lnk[MAXPATHLEN];
522                         int len;
523
524                         if (!S_ISDIR(st.st_mode)
525                             && (len = readlink(fname, lnk, MAXPATHLEN-1)) > 0) {
526                                 lnk[len] = 0;
527                                 /* A link already pointing to the
528                                  * right place -- no further action
529                                  * required. */
530                                 if (strcmp(lnk, file->u.link) == 0) {
531                                         if (itemizing) {
532                                                 itemize(file, 0, &st, 0,
533                                                         f_out, ndx);
534                                         }
535                                         set_perms(fname, file, &st,
536                                                   maybe_PERMS_REPORT);
537                                         return;
538                                 }
539                         }
540                         /* Not the right symlink (or not a symlink), so
541                          * delete it. */
542                         if (S_ISLNK(st.st_mode))
543                                 delete_file(fname, st.st_mode, DEL_TERSE);
544                         else {
545                                 delete_file(fname, st.st_mode, DEL_TERSE);
546                                 statret = -1;
547                         }
548                 }
549                 if (do_symlink(file->u.link,fname) != 0) {
550                         rsyserr(FERROR, errno, "symlink %s -> \"%s\" failed",
551                                 full_fname(fname), safe_fname(file->u.link));
552                 } else {
553                         set_perms(fname,file,NULL,0);
554                         if (itemizing) {
555                                 itemize(file, statret, &st, SID_UPDATING,
556                                         f_out, ndx);
557                         }
558                         if (code && verbose) {
559                                 rprintf(code, "%s -> %s\n", safe_fname(fname),
560                                         safe_fname(file->u.link));
561                         }
562                         if (remove_sent_files && !dry_run) {
563                                 char numbuf[4];
564                                 SIVAL(numbuf, 0, ndx);
565                                 send_msg(MSG_SUCCESS, numbuf, 4);
566                         }
567                 }
568 #endif
569                 return;
570         }
571
572         if (am_root && preserve_devices && IS_DEVICE(file->mode)) {
573                 if (statret != 0 ||
574                     st.st_mode != file->mode ||
575                     st.st_rdev != file->u.rdev) {
576                         if (IS_DEVICE(st.st_mode))
577                                 delete_file(fname, st.st_mode, DEL_TERSE);
578                         else {
579                                 delete_file(fname, st.st_mode, DEL_TERSE);
580                                 statret = -1;
581                         }
582                         if (verbose > 2) {
583                                 rprintf(FINFO,"mknod(%s,0%o,0x%x)\n",
584                                         safe_fname(fname),
585                                         (int)file->mode, (int)file->u.rdev);
586                         }
587                         if (do_mknod(fname,file->mode,file->u.rdev) != 0) {
588                                 rsyserr(FERROR, errno, "mknod %s failed",
589                                         full_fname(fname));
590                         } else {
591                                 set_perms(fname,file,NULL,0);
592                                 if (itemizing) {
593                                         itemize(file, statret, &st, SID_UPDATING,
594                                                 f_out, ndx);
595                                 }
596                                 if (code && verbose) {
597                                         rprintf(code, "%s\n",
598                                                 safe_fname(fname));
599                                 }
600                         }
601                 } else {
602                         if (itemizing) {
603                                 itemize(file, statret, &st, 0,
604                                         f_out, ndx);
605                         }
606                         set_perms(fname, file, &st, maybe_PERMS_REPORT);
607                 }
608                 return;
609         }
610
611         if (preserve_hard_links && hard_link_check(file, HL_CHECK_MASTER))
612                 return;
613
614         if (!S_ISREG(file->mode)) {
615                 rprintf(FINFO, "skipping non-regular file \"%s\"\n",
616                         safe_fname(fname));
617                 return;
618         }
619
620         fnamecmp = fname;
621         fnamecmp_type = FNAMECMP_FNAME;
622
623         if (statret != 0 && basis_dir[0] != NULL) {
624                 int fallback_match = -1;
625                 int match_level = 0;
626                 int i = 0;
627                 do {
628                         pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
629                                  basis_dir[i], fname);
630                         if (link_stat(fnamecmpbuf, &st, 0) == 0
631                             && S_ISREG(st.st_mode)) {
632                                 statret = 0;
633                                 if (link_dest) {
634                                         if (!match_level) {
635                                                 fallback_match = i;
636                                                 match_level = 1;
637                                         } else if (match_level == 2
638                                             && !unchanged_attrs(file, &st))
639                                                 continue;
640                                         if (!unchanged_file(fnamecmpbuf, file, &st))
641                                                 continue;
642                                         fallback_match = i;
643                                         match_level = 2;
644                                         if (!unchanged_attrs(file, &st))
645                                                 continue;
646                                 }
647                                 match_level = 3;
648                                 break;
649                         }
650                 } while (basis_dir[++i] != NULL);
651                 if (statret == 0) {
652                         if (match_level < 3) {
653                                 i = fallback_match;
654                                 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
655                                          basis_dir[i], fname);
656                         }
657 #ifdef HAVE_LINK
658                         if (link_dest && match_level == 3 && !dry_run) {
659                                 if (do_link(fnamecmpbuf, fname) < 0) {
660                                         if (verbose) {
661                                                 rsyserr(FINFO, errno,
662                                                         "link %s => %s",
663                                                         full_fname(fnamecmpbuf),
664                                                         safe_fname(fname));
665                                         }
666                                         fnamecmp = fnamecmpbuf;
667                                         fnamecmp_type = i;
668                                 }
669                         } else
670 #endif
671                         {
672                                 fnamecmp = fnamecmpbuf;
673                                 fnamecmp_type = i;
674                         }
675                 }
676         }
677
678         if (statret == 0 && !S_ISREG(st.st_mode)) {
679                 if (delete_file(fname, st.st_mode, DEL_TERSE) != 0)
680                         return;
681                 statret = -1;
682                 stat_errno = ENOENT;
683         }
684
685         if (partial_dir && (partialptr = partial_dir_fname(fname)) != NULL
686             && link_stat(partialptr, &partial_st, 0) == 0
687             && S_ISREG(partial_st.st_mode)) {
688                 if (statret != 0)
689                         goto prepare_to_open;
690         } else
691                 partialptr = NULL;
692
693         if (statret != 0 && fuzzy_basis && dry_run <= 1) {
694                 int j = find_fuzzy(file, fuzzy_dirlist);
695                 if (j >= 0) {
696                         fuzzy_file = fuzzy_dirlist->files[j];
697                         f_name_to(fuzzy_file, fnamecmpbuf);
698                         if (verbose > 2) {
699                                 rprintf(FINFO, "fuzzy basis selected for %s: %s\n",
700                                         safe_fname(fname), safe_fname(fnamecmpbuf));
701                         }
702                         st.st_mode = fuzzy_file->mode;
703                         st.st_size = fuzzy_file->length;
704                         st.st_mtime = fuzzy_file->modtime;
705                         statret = 0;
706                         fnamecmp = fnamecmpbuf;
707                         fnamecmp_type = FNAMECMP_FUZZY;
708                 }
709         }
710
711         if (statret != 0) {
712                 if (preserve_hard_links && hard_link_check(file, HL_SKIP))
713                         return;
714                 if (stat_errno == ENOENT)
715                         goto notify_others;
716                 if (verbose > 1) {
717                         rsyserr(FERROR, stat_errno,
718                                 "recv_generator: failed to stat %s",
719                                 full_fname(fname));
720                 }
721                 return;
722         }
723
724         if (opt_ignore_existing && fnamecmp_type == FNAMECMP_FNAME) {
725                 if (verbose > 1)
726                         rprintf(FINFO, "%s exists\n", safe_fname(fname));
727                 return;
728         }
729
730         if (update_only && fnamecmp_type == FNAMECMP_FNAME
731             && cmp_modtime(st.st_mtime, file->modtime) > 0) {
732                 if (verbose > 1)
733                         rprintf(FINFO, "%s is newer\n", safe_fname(fname));
734                 return;
735         }
736
737         if (!compare_dest && fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
738                 ;
739         else if (fnamecmp_type == FNAMECMP_FUZZY)
740                 ;
741         else if (unchanged_file(fnamecmp, file, &st)) {
742                 if (itemizing) {
743                         itemize(file, statret, &st,
744                                 fnamecmp_type == FNAMECMP_FNAME
745                                                ? 0 : SID_NO_DEST_AND_NO_UPDATE,
746                                 f_out, ndx);
747                 }
748                 if (fnamecmp_type == FNAMECMP_FNAME)
749                         set_perms(fname, file, &st, maybe_PERMS_REPORT);
750                 return;
751         }
752
753 prepare_to_open:
754         if (partialptr) {
755                 st = partial_st;
756                 fnamecmp = partialptr;
757                 fnamecmp_type = FNAMECMP_PARTIAL_DIR;
758                 statret = 0;
759         }
760
761         if (dry_run || read_batch)
762                 goto notify_others;
763         if (whole_file > 0) {
764                 if (statret == 0)
765                         statret = 1;
766                 goto notify_others;
767         }
768
769         if (fuzzy_basis) {
770                 int j = flist_find(fuzzy_dirlist, file);
771                 if (j >= 0) /* don't use changing file as future fuzzy basis */
772                         fuzzy_dirlist->files[j]->flags |= FLAG_NO_FUZZY;
773         }
774
775         /* open the file */
776         fd = do_open(fnamecmp, O_RDONLY, 0);
777
778         if (fd == -1) {
779                 rsyserr(FERROR, errno, "failed to open %s, continuing",
780                         full_fname(fnamecmp));
781             pretend_missing:
782                 /* pretend the file didn't exist */
783                 if (preserve_hard_links && hard_link_check(file, HL_SKIP))
784                         return;
785                 statret = -1;
786                 goto notify_others;
787         }
788
789         if (inplace && make_backups) {
790                 if (!(backupptr = get_backup_name(fname))) {
791                         close(fd);
792                         return;
793                 }
794                 if (!(back_file = make_file(fname, NULL, NO_FILTERS))) {
795                         close(fd);
796                         goto pretend_missing;
797                 }
798                 if (robust_unlink(backupptr) && errno != ENOENT) {
799                         rsyserr(FERROR, errno, "unlink %s",
800                                 full_fname(backupptr));
801                         free(back_file);
802                         close(fd);
803                         return;
804                 }
805                 if ((f_copy = do_open(backupptr,
806                     O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) {
807                         rsyserr(FERROR, errno, "open %s",
808                                 full_fname(backupptr));
809                         free(back_file);
810                         close(fd);
811                         return;
812                 }
813                 fnamecmp_type = FNAMECMP_BACKUP;
814         }
815
816         if (verbose > 3) {
817                 rprintf(FINFO, "gen mapped %s of size %.0f\n",
818                         safe_fname(fnamecmp), (double)st.st_size);
819         }
820
821         if (verbose > 2)
822                 rprintf(FINFO, "generating and sending sums for %d\n", ndx);
823
824 notify_others:
825         write_int(f_out, ndx);
826         if (itemizing) {
827                 int iflags = SID_UPDATING;
828                 if (always_checksum)
829                         iflags |= SID_REPORT_CHECKSUM;
830                 if (fnamecmp_type != FNAMECMP_FNAME)
831                         iflags |= SID_USING_ALT_BASIS;
832                 itemize(file, statret, &st, iflags, f_out, -1);
833         }
834         if (f_out_name >= 0) {
835                 write_byte(f_out_name, fnamecmp_type);
836                 if (fnamecmp_type == FNAMECMP_FUZZY) {
837                         uchar lenbuf[3], *lb = lenbuf;
838                         int len = strlen(fuzzy_file->basename);
839                         if (len > 0x7F) {
840 #if MAXPATHLEN > 0x7FFF
841                                 *lb++ = len / 0x10000 + 0x80;
842                                 *lb++ = len / 0x100;
843 #else
844                                 *lb++ = len / 0x100 + 0x80;
845 #endif
846                         }
847                         *lb = len;
848                         write_buf(f_out_name, (char*)lenbuf, lb - lenbuf + 1);
849                         write_buf(f_out_name, fuzzy_file->basename, len);
850                 }
851         }
852
853         if (dry_run || read_batch)
854                 return;
855
856         if (statret == 0) {
857                 generate_and_send_sums(fd, st.st_size, f_out, f_copy);
858
859                 if (f_copy >= 0) {
860                         close(f_copy);
861                         set_perms(backupptr, back_file, NULL, 0);
862                         if (verbose > 1) {
863                                 rprintf(FINFO, "backed up %s to %s\n",
864                                         safe_fname(fname), safe_fname(backupptr));
865                         }
866                         free(back_file);
867                 }
868
869                 close(fd);
870         } else
871                 write_sum_head(f_out, NULL);
872 }
873
874
875 void generate_files(int f_out, struct file_list *flist, char *local_name,
876                     int f_out_name)
877 {
878         int i;
879         int phase = 0;
880         char fbuf[MAXPATHLEN];
881         int need_retouch_dir_times = preserve_times && !omit_dir_times;
882         int need_retouch_dir_perms = 0;
883         int save_only_existing = only_existing;
884         int save_opt_ignore_existing = opt_ignore_existing;
885         int allowed_lull = protocol_version >= 29 ? io_timeout / 2 : 0;
886
887         if (verbose > 2) {
888                 rprintf(FINFO, "generator starting pid=%ld count=%d\n",
889                         (long)getpid(), flist->count);
890         }
891
892         if (verbose >= 2) {
893                 rprintf(FINFO, "delta-transmission %s\n",
894                         whole_file > 0
895                         ? "disabled for local transfer or --whole-file"
896                         : "enabled");
897         }
898
899         if (protocol_version < 29)
900                 io_timeout = 0; /* kluge for older protocol versions */
901
902         for (i = 0; i < flist->count; i++) {
903                 struct file_struct *file = flist->files[i];
904                 struct file_struct copy;
905
906                 if (!file->basename)
907                         continue;
908
909                 /* We need to ensure that any dirs we create have writeable
910                  * permissions during the time we are putting files within
911                  * them.  This is then fixed after the transfer is done. */
912                 if (!am_root && S_ISDIR(file->mode) && !(file->mode & S_IWUSR)) {
913                         copy = *file;
914                         copy.mode |= S_IWUSR; /* user write */
915                         file = &copy;
916                         need_retouch_dir_perms = 1;
917                 }
918
919                 recv_generator(local_name ? local_name : f_name_to(file, fbuf),
920                                flist, file, i, f_out, f_out_name);
921
922                 if (allowed_lull && !(i % 100))
923                         maybe_send_keepalive(allowed_lull, flist->count);
924         }
925         recv_generator(NULL, NULL, NULL, 0, -1, -1);
926         if (delete_during)
927                 delete_in_dir(NULL, NULL, NULL);
928
929         phase++;
930         csum_length = SUM_LENGTH;
931         only_existing = max_size = opt_ignore_existing = 0;
932         update_only = always_checksum = size_only = 0;
933         ignore_times = 1;
934
935         /* We expect to just sit around now, so don't exit on a timeout.
936          * If we really get a timeout then the other process should exit. */
937         ignore_timeout = 1;
938
939         if (verbose > 2)
940                 rprintf(FINFO,"generate_files phase=%d\n",phase);
941
942         write_int(f_out, -1);
943
944         /* files can cycle through the system more than once
945          * to catch initial checksum errors */
946         while ((i = get_redo_num()) != -1) {
947                 struct file_struct *file = flist->files[i];
948                 recv_generator(local_name ? local_name : f_name_to(file, fbuf),
949                                flist, file, i, f_out, f_out_name);
950                 if (allowed_lull)
951                         maybe_send_keepalive(allowed_lull, flist->count);
952         }
953
954         phase++;
955         only_existing = save_only_existing;
956         opt_ignore_existing = save_opt_ignore_existing;
957
958         if (verbose > 2)
959                 rprintf(FINFO,"generate_files phase=%d\n",phase);
960
961         write_int(f_out, -1);
962
963         /* Read post-redo-phase MSG_DONE and any prior messages. */
964         get_redo_num();
965
966         if (preserve_hard_links)
967                 do_hard_links();
968
969         if ((need_retouch_dir_perms || need_retouch_dir_times)
970             && !list_only && !local_name && !dry_run) {
971                 /* Now we need to fix any directory permissions that were
972                  * modified during the transfer and/or re-set any tweaked
973                  * modified-time values. */
974                 for (i = 0; i < flist->count; i++) {
975                         struct file_struct *file = flist->files[i];
976                         if (!file->basename || !S_ISDIR(file->mode))
977                                 continue;
978                         if (!need_retouch_dir_times && file->mode & S_IWUSR)
979                                 continue;
980                         recv_generator(local_name ? local_name : f_name(file),
981                                        flist, file, i, -1, -1);
982                 }
983         }
984         recv_generator(NULL, NULL, NULL, 0, -1, -1);
985
986         if (verbose > 2)
987                 rprintf(FINFO,"generate_files finished\n");
988 }