Tweaked a couple things in try_dests_reg().
[rsync/rsync.git] / generator.c
1 /*
2  * Routines that are exclusive to the generator process.
3  *
4  * Copyright (C) 1996-2000 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2003, 2004, 2005, 2006 Wayne Davison
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 along
20  * with this program; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
22  */
23
24 #include "rsync.h"
25
26 extern int verbose;
27 extern int dry_run;
28 extern int do_xfers;
29 extern int log_format_has_i;
30 extern int logfile_format_has_i;
31 extern int am_root;
32 extern int am_server;
33 extern int am_daemon;
34 extern int do_progress;
35 extern int recurse;
36 extern int relative_paths;
37 extern int implied_dirs;
38 extern int keep_dirlinks;
39 extern int preserve_links;
40 extern int preserve_devices;
41 extern int preserve_specials;
42 extern int preserve_hard_links;
43 extern int preserve_perms;
44 extern int preserve_uid;
45 extern int preserve_gid;
46 extern int preserve_times;
47 extern int omit_dir_times;
48 extern int delete_mode;
49 extern int delete_before;
50 extern int delete_during;
51 extern int delete_after;
52 extern int module_id;
53 extern int ignore_errors;
54 extern int remove_sent_files;
55 extern int delay_updates;
56 extern int update_only;
57 extern int ignore_existing;
58 extern int ignore_non_existing;
59 extern int inplace;
60 extern int append_mode;
61 extern int make_backups;
62 extern int csum_length;
63 extern int ignore_times;
64 extern int size_only;
65 extern OFF_T max_size;
66 extern OFF_T min_size;
67 extern int io_error;
68 extern int allowed_lull;
69 extern int sock_f_out;
70 extern int ignore_timeout;
71 extern int protocol_version;
72 extern int fuzzy_basis;
73 extern int always_checksum;
74 extern int checksum_len;
75 extern char *partial_dir;
76 extern char *basis_dir[];
77 extern int compare_dest;
78 extern int copy_dest;
79 extern int link_dest;
80 extern int whole_file;
81 extern int list_only;
82 extern int read_batch;
83 extern int safe_symlinks;
84 extern long block_size; /* "long" because popt can't set an int32. */
85 extern int max_delete;
86 extern int force_delete;
87 extern int one_file_system;
88 extern struct stats stats;
89 extern dev_t filesystem_dev;
90 extern char *backup_dir;
91 extern char *backup_suffix;
92 extern int backup_suffix_len;
93 extern struct file_list *the_file_list;
94 extern struct filter_list_struct server_filter_list;
95
96 static int deletion_count = 0; /* used to implement --max-delete */
97
98 /* For calling delete_file() */
99 #define DEL_FORCE_RECURSE       (1<<1) /* recurse even w/o --force */
100 #define DEL_TERSE               (1<<3)
101
102
103 static int is_backup_file(char *fn)
104 {
105         int k = strlen(fn) - backup_suffix_len;
106         return k > 0 && strcmp(fn+k, backup_suffix) == 0;
107 }
108
109
110 /* Delete a file or directory.  If DEL_FORCE_RECURSE is set in the flags, or if
111  * force_delete is set, this will delete recursively.
112  *
113  * Note that fname must point to a MAXPATHLEN buffer if the mode indicates it's
114  * a directory! (The buffer is used for recursion, but returned unchanged.)
115  */
116 static int delete_item(char *fname, int mode, int flags)
117 {
118         struct file_list *dirlist;
119         int j, dlen, zap_dir, ok;
120         unsigned remainder;
121         void *save_filters;
122         char *p;
123
124         if (!S_ISDIR(mode)) {
125                 if (max_delete && ++deletion_count > max_delete)
126                         return 0;
127                 if (make_backups && (backup_dir || !is_backup_file(fname)))
128                         ok = make_backup(fname);
129                 else
130                         ok = robust_unlink(fname) == 0;
131                 if (ok) {
132                         if (!(flags & DEL_TERSE))
133                                 log_delete(fname, mode);
134                         return 0;
135                 }
136                 if (errno == ENOENT) {
137                         deletion_count--;
138                         return 0;
139                 }
140                 rsyserr(FERROR, errno, "delete_file: unlink %s failed",
141                         full_fname(fname));
142                 return -1;
143         }
144
145         zap_dir = flags & DEL_FORCE_RECURSE || force_delete;
146         if ((max_delete && ++deletion_count > max_delete)
147             || (dry_run && zap_dir)) {
148                 ok = 0;
149                 errno = ENOTEMPTY;
150         } else if (make_backups && !backup_dir && !is_backup_file(fname)
151             && !(flags & DEL_FORCE_RECURSE))
152                 ok = make_backup(fname);
153         else
154                 ok = do_rmdir(fname) == 0;
155         if (ok) {
156                 if (!(flags & DEL_TERSE))
157                         log_delete(fname, mode);
158                 return 0;
159         }
160         if (errno == ENOENT) {
161                 deletion_count--;
162                 return 0;
163         }
164         if (!zap_dir) {
165                 rsyserr(FERROR, errno, "delete_file: rmdir %s failed",
166                         full_fname(fname));
167                 return -1;
168         }
169         flags |= DEL_FORCE_RECURSE; /* mark subdir dels as not "in the way" */
170         deletion_count--;
171
172         dlen = strlen(fname);
173         save_filters = push_local_filters(fname, dlen);
174
175         dirlist = get_dirlist(fname, dlen, 0);
176
177         p = fname + dlen;
178         if (dlen != 1 || *fname != '/')
179                 *p++ = '/';
180         remainder = MAXPATHLEN - (p - fname);
181
182         for (j = dirlist->count; j--; ) {
183                 struct file_struct *fp = dirlist->files[j];
184
185                 if (fp->flags & FLAG_MOUNT_POINT)
186                         continue;
187
188                 strlcpy(p, fp->basename, remainder);
189                 delete_item(fname, fp->mode, flags & ~DEL_TERSE);
190         }
191         flist_free(dirlist);
192
193         fname[dlen] = '\0';
194
195         pop_local_filters(save_filters);
196
197         if (max_delete && ++deletion_count > max_delete)
198                 return 0;
199
200         if (do_rmdir(fname) == 0) {
201                 if (!(flags & DEL_TERSE))
202                         log_delete(fname, mode);
203         } else if (errno != ENOTEMPTY && errno != EEXIST && errno != ENOENT) {
204                 rsyserr(FERROR, errno, "delete_file: rmdir %s failed",
205                         full_fname(fname));
206                 return -1;
207         }
208
209         return 0;
210 }
211
212
213 /* This function is used to implement per-directory deletion, and is used by
214  * all the --delete-WHEN options.  Note that the fbuf pointer must point to a
215  * MAXPATHLEN buffer with the name of the directory in it (the functions we
216  * call will append names onto the end, but the old dir value will be restored
217  * on exit). */
218 static void delete_in_dir(struct file_list *flist, char *fbuf,
219                           struct file_struct *file, STRUCT_STAT *stp)
220 {
221         static int min_depth = MAXPATHLEN, cur_depth = -1;
222         static void *filt_array[MAXPATHLEN/2+1];
223         static int already_warned = 0;
224         struct file_list *dirlist;
225         char delbuf[MAXPATHLEN];
226         int dlen, i;
227
228         if (!flist) {
229                 while (cur_depth >= min_depth)
230                         pop_local_filters(filt_array[cur_depth--]);
231                 min_depth = MAXPATHLEN;
232                 cur_depth = -1;
233                 return;
234         }
235
236         if (verbose > 2)
237                 rprintf(FINFO, "delete_in_dir(%s)\n", fbuf);
238
239         if (allowed_lull)
240                 maybe_send_keepalive();
241
242         if (file->dir.depth >= MAXPATHLEN/2+1)
243                 return; /* Impossible... */
244
245         if (io_error && !(lp_ignore_errors(module_id) || ignore_errors)) {
246                 if (already_warned)
247                         return;
248                 rprintf(FINFO,
249                         "IO error encountered -- skipping file deletion\n");
250                 already_warned = 1;
251                 return;
252         }
253
254         while (cur_depth >= file->dir.depth && cur_depth >= min_depth)
255                 pop_local_filters(filt_array[cur_depth--]);
256         cur_depth = file->dir.depth;
257         if (min_depth > cur_depth)
258                 min_depth = cur_depth;
259         dlen = strlen(fbuf);
260         filt_array[cur_depth] = push_local_filters(fbuf, dlen);
261
262         if (one_file_system) {
263                 if (file->flags & FLAG_TOP_DIR)
264                         filesystem_dev = stp->st_dev;
265                 else if (filesystem_dev != stp->st_dev)
266                         return;
267         }
268
269         dirlist = get_dirlist(fbuf, dlen, 0);
270
271         /* If an item in dirlist is not found in flist, delete it
272          * from the filesystem. */
273         for (i = dirlist->count; i--; ) {
274                 struct file_struct *fp = dirlist->files[i];
275                 if (!fp->basename || fp->flags & FLAG_MOUNT_POINT)
276                         continue;
277                 if (flist_find(flist, fp) < 0) {
278                         f_name(fp, delbuf);
279                         delete_item(delbuf, fp->mode, DEL_FORCE_RECURSE);
280                 }
281         }
282
283         flist_free(dirlist);
284 }
285
286 /* This deletes any files on the receiving side that are not present on the
287  * sending side.  This is used by --delete-before and --delete-after. */
288 static void do_delete_pass(struct file_list *flist)
289 {
290         char fbuf[MAXPATHLEN];
291         STRUCT_STAT st;
292         int j;
293
294         if (dry_run > 1 /* destination doesn't exist yet */
295          || list_only)
296                 return;
297
298         for (j = 0; j < flist->count; j++) {
299                 struct file_struct *file = flist->files[j];
300
301                 if (!(file->flags & FLAG_DEL_HERE))
302                         continue;
303
304                 f_name(file, fbuf);
305                 if (verbose > 1 && file->flags & FLAG_TOP_DIR)
306                         rprintf(FINFO, "deleting in %s\n", fbuf);
307
308                 if (link_stat(fbuf, &st, keep_dirlinks) < 0
309                  || !S_ISDIR(st.st_mode))
310                         continue;
311
312                 delete_in_dir(flist, fbuf, file, &st);
313         }
314         delete_in_dir(NULL, NULL, NULL, NULL);
315
316         if (do_progress && !am_server)
317                 rprintf(FINFO, "                    \r");
318 }
319
320 int unchanged_attrs(struct file_struct *file, STRUCT_STAT *st)
321 {
322         if (preserve_perms
323          && (st->st_mode & CHMOD_BITS) != (file->mode & CHMOD_BITS))
324                 return 0;
325
326         if (am_root && preserve_uid && st->st_uid != file->uid)
327                 return 0;
328
329         if (preserve_gid && file->gid != GID_NONE && st->st_gid != file->gid)
330                 return 0;
331
332         return 1;
333 }
334
335 void itemize(struct file_struct *file, int ndx, int statret, STRUCT_STAT *st,
336              int32 iflags, uchar fnamecmp_type, char *xname)
337 {
338         if (statret >= 0) { /* A from-dest-dir statret can == 1! */
339                 int keep_time = !preserve_times ? 0
340                     : S_ISDIR(file->mode) ? !omit_dir_times
341                     : !S_ISLNK(file->mode);
342
343                 if (S_ISREG(file->mode) && file->length != st->st_size)
344                         iflags |= ITEM_REPORT_SIZE;
345                 if ((iflags & (ITEM_TRANSFER|ITEM_LOCAL_CHANGE) && !keep_time
346                      && (!(iflags & ITEM_XNAME_FOLLOWS) || *xname))
347                     || (keep_time && cmp_time(file->modtime, st->st_mtime) != 0))
348                         iflags |= ITEM_REPORT_TIME;
349                 if ((file->mode & CHMOD_BITS) != (st->st_mode & CHMOD_BITS))
350                         iflags |= ITEM_REPORT_PERMS;
351                 if (preserve_uid && am_root && file->uid != st->st_uid)
352                         iflags |= ITEM_REPORT_OWNER;
353                 if (preserve_gid && file->gid != GID_NONE
354                     && st->st_gid != file->gid)
355                         iflags |= ITEM_REPORT_GROUP;
356         } else
357                 iflags |= ITEM_IS_NEW;
358
359         iflags &= 0xffff;
360         if ((iflags & SIGNIFICANT_ITEM_FLAGS || verbose > 1
361           || log_format_has_i > 1 || (xname && *xname)) && !read_batch) {
362                 if (protocol_version >= 29) {
363                         if (ndx >= 0)
364                                 write_int(sock_f_out, ndx);
365                         write_shortint(sock_f_out, iflags);
366                         if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
367                                 write_byte(sock_f_out, fnamecmp_type);
368                         if (iflags & ITEM_XNAME_FOLLOWS)
369                                 write_vstring(sock_f_out, xname, strlen(xname));
370                 } else if (ndx >= 0)
371                         log_item(file, &stats, iflags, xname);
372         }
373 }
374
375
376 /* Perform our quick-check heuristic for determining if a file is unchanged. */
377 int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
378 {
379         if (st->st_size != file->length)
380                 return 0;
381
382         /* if always checksum is set then we use the checksum instead
383            of the file time to determine whether to sync */
384         if (always_checksum && S_ISREG(st->st_mode)) {
385                 char sum[MD4_SUM_LENGTH];
386                 file_checksum(fn, sum, st->st_size);
387                 return memcmp(sum, file->u.sum, checksum_len) == 0;
388         }
389
390         if (size_only)
391                 return 1;
392
393         if (ignore_times)
394                 return 0;
395
396         return cmp_time(st->st_mtime, file->modtime) == 0;
397 }
398
399
400 /*
401  * set (initialize) the size entries in the per-file sum_struct
402  * calculating dynamic block and checksum sizes.
403  *
404  * This is only called from generate_and_send_sums() but is a separate
405  * function to encapsulate the logic.
406  *
407  * The block size is a rounded square root of file length.
408  *
409  * The checksum size is determined according to:
410  *     blocksum_bits = BLOCKSUM_BIAS + 2*log2(file_len) - log2(block_len)
411  * provided by Donovan Baarda which gives a probability of rsync
412  * algorithm corrupting data and falling back using the whole md4
413  * checksums.
414  *
415  * This might be made one of several selectable heuristics.
416  */
417 static void sum_sizes_sqroot(struct sum_struct *sum, int64 len)
418 {
419         int32 blength;
420         int s2length;
421
422         if (block_size)
423                 blength = block_size;
424         else if (len <= BLOCK_SIZE * BLOCK_SIZE)
425                 blength = BLOCK_SIZE;
426         else {
427                 int32 c;
428                 int64 l;
429                 int cnt;
430                 for (c = 1, l = len, cnt = 0; l >>= 2; c <<= 1, cnt++) {}
431                 if (cnt >= 31 || c >= MAX_BLOCK_SIZE)
432                         blength = MAX_BLOCK_SIZE;
433                 else {
434                     blength = 0;
435                     do {
436                             blength |= c;
437                             if (len < (int64)blength * blength)
438                                     blength &= ~c;
439                             c >>= 1;
440                     } while (c >= 8);   /* round to multiple of 8 */
441                     blength = MAX(blength, BLOCK_SIZE);
442                 }
443         }
444
445         if (protocol_version < 27) {
446                 s2length = csum_length;
447         } else if (csum_length == SUM_LENGTH) {
448                 s2length = SUM_LENGTH;
449         } else {
450                 int32 c;
451                 int64 l;
452                 int b = BLOCKSUM_BIAS;
453                 for (l = len; l >>= 1; b += 2) {}
454                 for (c = blength; c >>= 1 && b; b--) {}
455                 /* add a bit, subtract rollsum, round up. */
456                 s2length = (b + 1 - 32 + 7) / 8; /* --optimize in compiler-- */
457                 s2length = MAX(s2length, csum_length);
458                 s2length = MIN(s2length, SUM_LENGTH);
459         }
460
461         sum->flength    = len;
462         sum->blength    = blength;
463         sum->s2length   = s2length;
464         sum->remainder  = len % blength;
465         sum->count      = len / blength + (sum->remainder != 0);
466
467         if (sum->count && verbose > 2) {
468                 rprintf(FINFO,
469                         "count=%.0f rem=%ld blength=%ld s2length=%d flength=%.0f\n",
470                         (double)sum->count, (long)sum->remainder, (long)sum->blength,
471                         sum->s2length, (double)sum->flength);
472         }
473 }
474
475
476 /*
477  * Generate and send a stream of signatures/checksums that describe a buffer
478  *
479  * Generate approximately one checksum every block_len bytes.
480  */
481 static void generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy)
482 {
483         int32 i;
484         struct map_struct *mapbuf;
485         struct sum_struct sum;
486         OFF_T offset = 0;
487
488         sum_sizes_sqroot(&sum, len);
489         write_sum_head(f_out, &sum);
490
491         if (append_mode > 0 && f_copy < 0)
492                 return;
493
494         if (len > 0)
495                 mapbuf = map_file(fd, len, MAX_MAP_SIZE, sum.blength);
496         else
497                 mapbuf = NULL;
498
499         for (i = 0; i < sum.count; i++) {
500                 int32 n1 = (int32)MIN(len, (OFF_T)sum.blength);
501                 char *map = map_ptr(mapbuf, offset, n1);
502                 char sum2[SUM_LENGTH];
503                 uint32 sum1;
504
505                 len -= n1;
506                 offset += n1;
507
508                 if (f_copy >= 0) {
509                         full_write(f_copy, map, n1);
510                         if (append_mode > 0)
511                                 continue;
512                 }
513
514                 sum1 = get_checksum1(map, n1);
515                 get_checksum2(map, n1, sum2);
516
517                 if (verbose > 3) {
518                         rprintf(FINFO,
519                                 "chunk[%.0f] offset=%.0f len=%ld sum1=%08lx\n",
520                                 (double)i, (double)offset - n1, (long)n1,
521                                 (unsigned long)sum1);
522                 }
523                 write_int(f_out, sum1);
524                 write_buf(f_out, sum2, sum.s2length);
525         }
526
527         if (mapbuf)
528                 unmap_file(mapbuf);
529 }
530
531
532 /* Try to find a filename in the same dir as "fname" with a similar name. */
533 static int find_fuzzy(struct file_struct *file, struct file_list *dirlist)
534 {
535         int fname_len, fname_suf_len;
536         const char *fname_suf, *fname = file->basename;
537         uint32 lowest_dist = 25 << 16; /* ignore a distance greater than 25 */
538         int j, lowest_j = -1;
539
540         fname_len = strlen(fname);
541         fname_suf = find_filename_suffix(fname, fname_len, &fname_suf_len);
542
543         for (j = 0; j < dirlist->count; j++) {
544                 struct file_struct *fp = dirlist->files[j];
545                 const char *suf, *name;
546                 int len, suf_len;
547                 uint32 dist;
548
549                 if (!S_ISREG(fp->mode) || !fp->length
550                     || fp->flags & FLAG_NO_FUZZY)
551                         continue;
552
553                 name = fp->basename;
554
555                 if (fp->length == file->length
556                     && cmp_time(fp->modtime, file->modtime) == 0) {
557                         if (verbose > 4) {
558                                 rprintf(FINFO,
559                                         "fuzzy size/modtime match for %s\n",
560                                         name);
561                         }
562                         return j;
563                 }
564
565                 len = strlen(name);
566                 suf = find_filename_suffix(name, len, &suf_len);
567
568                 dist = fuzzy_distance(name, len, fname, fname_len);
569                 /* Add some extra weight to how well the suffixes match. */
570                 dist += fuzzy_distance(suf, suf_len, fname_suf, fname_suf_len)
571                       * 10;
572                 if (verbose > 4) {
573                         rprintf(FINFO, "fuzzy distance for %s = %d.%05d\n",
574                                 name, (int)(dist>>16), (int)(dist&0xFFFF));
575                 }
576                 if (dist <= lowest_dist) {
577                         lowest_dist = dist;
578                         lowest_j = j;
579                 }
580         }
581
582         return lowest_j;
583 }
584
585 void check_for_finished_hlinks(int itemizing, enum logcode code)
586 {
587         struct file_struct *file;
588         int ndx;
589
590         while ((ndx = get_hlink_num()) != -1) {
591                 if (ndx < 0 || ndx >= the_file_list->count)
592                         continue;
593
594                 file = the_file_list->files[ndx];
595                 if (!file->link_u.links)
596                         continue;
597
598                 hard_link_cluster(file, ndx, itemizing, code);
599         }
600 }
601
602 /* This is only called for regular files.  We return -2 if we've finished
603  * handling the file, -1 if no dest-linking occurred, or a non-negative
604  * value if we found an alternate basis file. */
605 static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
606                          char *cmpbuf, STRUCT_STAT *stp, int itemizing,
607                          int maybe_ATTRS_REPORT, enum logcode code)
608 {
609         int save_ignore_times = ignore_times;
610         int best_match = -1;
611         int match_level = 0;
612         int j = 0;
613
614         /* We can't let ignore_times affect the unchanged_file() test in
615          * an alternate-dest dir or we will never find any matches. */
616         ignore_times = 0;
617
618         do {
619                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
620                 if (link_stat(cmpbuf, stp, 0) < 0 || !S_ISREG(stp->st_mode))
621                         continue;
622                 switch (match_level) {
623                 case 0:
624                         best_match = j;
625                         match_level = 1;
626                         /* FALL THROUGH */
627                 case 1:
628                         if (!unchanged_file(cmpbuf, file, stp))
629                                 continue;
630                         best_match = j;
631                         match_level = 2;
632                         /* FALL THROUGH */
633                 case 2:
634                         if (!unchanged_attrs(file, stp))
635                                 continue;
636                         if (always_checksum && preserve_times
637                          && cmp_time(stp->st_mtime, file->modtime))
638                                 continue;
639                         best_match = j;
640                         match_level = 3;
641                         break;
642                 }
643                 break;
644         } while (basis_dir[++j] != NULL);
645
646         ignore_times = save_ignore_times;
647
648         if (!match_level)
649                 return -1;
650
651         if (j != best_match) {
652                 j = best_match;
653                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
654                 if (link_stat(cmpbuf, stp, 0) < 0)
655                         match_level = 0;
656         }
657
658         if (match_level == 3 && !copy_dest) {
659 #ifdef SUPPORT_HARD_LINKS
660                 if (link_dest) {
661                         if (hard_link_one(file, ndx, fname, 0, stp,
662                                           cmpbuf, 1,
663                                           itemizing && verbose > 1,
664                                           code) < 0)
665                                 goto try_a_copy;
666                         if (preserve_hard_links && file->link_u.links)
667                                 hard_link_cluster(file, ndx, itemizing, code);
668                 } else
669 #endif
670                 if (itemizing)
671                         itemize(file, ndx, 0, stp, 0, 0, NULL);
672                 if (verbose > 1 && maybe_ATTRS_REPORT) {
673                         code = logfile_format_has_i || dry_run
674                              ? FCLIENT : FINFO;
675                         rprintf(code, "%s is uptodate\n", fname);
676                 }
677                 return -2;
678         }
679
680         if (match_level >= 2) {
681           try_a_copy: /* Copy the file locally. */
682                 if (copy_file(cmpbuf, fname, file->mode) < 0) {
683                         if (verbose) {
684                                 rsyserr(FINFO, errno, "copy_file %s => %s",
685                                         full_fname(cmpbuf), fname);
686                         }
687                         return -1;
688                 }
689                 if (itemizing)
690                         itemize(file, ndx, 0, stp, ITEM_LOCAL_CHANGE, 0, NULL);
691                 set_file_attrs(fname, file, NULL, 0);
692                 if (maybe_ATTRS_REPORT
693                  && ((!itemizing && verbose && match_level == 2)
694                   || (verbose > 1 && match_level == 3))) {
695                         code = logfile_format_has_i || dry_run
696                              ? FCLIENT : FINFO;
697                         rprintf(code, "%s%s\n", fname,
698                                 match_level == 3 ? " is uptodate" : "");
699                 }
700                 if (preserve_hard_links && file->link_u.links)
701                         hard_link_cluster(file, ndx, itemizing, code);
702                 return -2;
703         }
704
705         return FNAMECMP_BASIS_DIR_LOW + j;
706 }
707
708 /* This is only called for non-regular files.  We return -2 if we've finished
709  * handling the file, or -1 if no dest-linking occurred. */
710 static int try_dests_non(struct file_struct *file, char *fname, int ndx,
711                          int itemizing, int maybe_ATTRS_REPORT,
712                          enum logcode code)
713 {
714         char fnamebuf[MAXPATHLEN];
715         STRUCT_STAT st;
716         int i = 0;
717
718         do {
719                 pathjoin(fnamebuf, MAXPATHLEN, basis_dir[i], fname);
720                 if (link_stat(fnamebuf, &st, 0) < 0 || S_ISDIR(st.st_mode)
721                  || !unchanged_attrs(file, &st))
722                         continue;
723                 if (S_ISLNK(file->mode)) {
724 #ifdef SUPPORT_LINKS
725                         char lnk[MAXPATHLEN];
726                         int len;
727                         if ((len = readlink(fnamebuf, lnk, MAXPATHLEN-1)) <= 0)
728                                 continue;
729                         lnk[len] = '\0';
730                         if (strcmp(lnk, file->u.link) != 0)
731 #endif
732                                 continue;
733                 } else if (IS_SPECIAL(file->mode)) {
734                         if (!IS_SPECIAL(st.st_mode) || st.st_rdev != file->u.rdev)
735                                 continue;
736                 } else if (IS_DEVICE(file->mode)) {
737                         if (!IS_DEVICE(st.st_mode) || st.st_rdev != file->u.rdev)
738                                 continue;
739                 } else {
740                         rprintf(FERROR,
741                                 "internal: try_dests_non() called with invalid mode (%o)\n",
742                                 (int)file->mode);
743                         exit_cleanup(RERR_UNSUPPORTED);
744                 }
745 #ifdef SUPPORT_HARD_LINKS
746                 if (link_dest
747 #ifndef CAN_HARDLINK_SYMLINK
748                  && !S_ISLNK(file->mode)
749 #endif
750 #ifndef CAN_HARDLINK_SPECIAL
751                  && !IS_SPECIAL(file->mode) && !IS_DEVICE(file->mode)
752 #endif
753                 ) {
754                         if (do_link(fnamebuf, fname) < 0) {
755                                 rsyserr(FERROR, errno,
756                                         "failed to hard-link %s with %s",
757                                         fnamebuf, fname);
758                                 break;
759                         }
760                         if (preserve_hard_links && file->link_u.links)
761                                 hard_link_cluster(file, ndx, itemizing, code);
762                 }
763 #endif
764                 if (itemizing && log_format_has_i && verbose > 1) {
765                         int changes = compare_dest ? 0 : ITEM_LOCAL_CHANGE
766                                     + (link_dest ? ITEM_XNAME_FOLLOWS : 0);
767                         char *lp = link_dest ? "" : NULL;
768                         itemize(file, ndx, 0, &st, changes, 0, lp);
769                 }
770                 if (verbose > 1 && maybe_ATTRS_REPORT) {
771                         code = logfile_format_has_i || dry_run
772                              ? FCLIENT : FINFO;
773                         rprintf(code, "%s is uptodate\n", fname);
774                 }
775                 return -2;
776         } while (basis_dir[++i] != NULL);
777
778         return -1;
779 }
780
781 static int phase = 0;
782
783 /* Acts on the_file_list->file's ndx'th item, whose name is fname.  If a dir,
784  * make sure it exists, and has the right permissions/timestamp info.  For
785  * all other non-regular files (symlinks, etc.) we create them here.  For
786  * regular files that have changed, we try to find a basis file and then
787  * start sending checksums.
788  *
789  * When fname is non-null, it must point to a MAXPATHLEN buffer!
790  *
791  * Note that f_out is set to -1 when doing final directory-permission and
792  * modification-time repair. */
793 static void recv_generator(char *fname, struct file_struct *file, int ndx,
794                            int itemizing, int maybe_ATTRS_REPORT,
795                            enum logcode code, int f_out)
796 {
797         static int missing_below = -1, excluded_below = -1;
798         static char *parent_dirname = "";
799         static struct file_list *fuzzy_dirlist = NULL;
800         static int need_fuzzy_dirlist = 0;
801         struct file_struct *fuzzy_file = NULL;
802         int fd = -1, f_copy = -1;
803         STRUCT_STAT st, real_st, partial_st;
804         struct file_struct *back_file = NULL;
805         int statret, real_ret, stat_errno;
806         char *fnamecmp, *partialptr, *backupptr = NULL;
807         char fnamecmpbuf[MAXPATHLEN];
808         uchar fnamecmp_type;
809         int del_opts = DEL_TERSE | (delete_mode ? DEL_FORCE_RECURSE : 0);
810
811         if (list_only)
812                 return;
813
814         if (!fname) {
815                 if (fuzzy_dirlist) {
816                         flist_free(fuzzy_dirlist);
817                         fuzzy_dirlist = NULL;
818                 }
819                 if (missing_below >= 0) {
820                         dry_run--;
821                         missing_below = -1;
822                 }
823                 parent_dirname = "";
824                 return;
825         }
826
827         if (verbose > 2)
828                 rprintf(FINFO, "recv_generator(%s,%d)\n", fname, ndx);
829
830         if (server_filter_list.head) {
831                 if (excluded_below >= 0) {
832                         if (file->dir.depth > excluded_below)
833                                 goto skipping;
834                         excluded_below = -1;
835                 }
836                 if (check_filter(&server_filter_list, fname,
837                                  S_ISDIR(file->mode)) < 0) {
838                         if (S_ISDIR(file->mode))
839                                 excluded_below = file->dir.depth;
840                   skipping:
841                         if (verbose) {
842                                 rprintf(FINFO,
843                                         "skipping server-excluded file \"%s\"\n",
844                                         fname);
845                         }
846                         return;
847                 }
848         }
849
850         if (missing_below >= 0 && file->dir.depth <= missing_below) {
851                 dry_run--;
852                 missing_below = -1;
853         }
854         if (dry_run > 1) {
855                 statret = -1;
856                 stat_errno = ENOENT;
857         } else {
858                 char *dn = file->dirname ? file->dirname : ".";
859                 if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) {
860                         if (relative_paths && !implied_dirs
861                          && safe_stat(dn, &st) < 0
862                          && create_directory_path(fname) < 0) {
863                                 rsyserr(FERROR, errno,
864                                         "recv_generator: mkdir %s failed",
865                                         full_fname(dn));
866                         }
867                         if (fuzzy_dirlist) {
868                                 flist_free(fuzzy_dirlist);
869                                 fuzzy_dirlist = NULL;
870                         }
871                         if (fuzzy_basis)
872                                 need_fuzzy_dirlist = 1;
873                 }
874                 parent_dirname = dn;
875
876                 if (need_fuzzy_dirlist && S_ISREG(file->mode)) {
877                         fuzzy_dirlist = get_dirlist(dn, -1, 1);
878                         need_fuzzy_dirlist = 0;
879                 }
880
881                 statret = link_stat(fname, &st,
882                                     keep_dirlinks && S_ISDIR(file->mode));
883                 stat_errno = errno;
884         }
885
886         if (ignore_non_existing && statret == -1 && stat_errno == ENOENT) {
887                 if (verbose > 1) {
888                         rprintf(FINFO, "not creating new %s \"%s\"\n",
889                                 S_ISDIR(file->mode) ? "directory" : "file",
890                                 fname);
891                 }
892                 return;
893         }
894
895         /* If we're not preserving permissions, change the file-list's
896          * mode based on the local permissions and some heuristics. */
897         if (!preserve_perms) {
898                 int exists = statret == 0
899                           && S_ISDIR(st.st_mode) == S_ISDIR(file->mode);
900                 file->mode = dest_mode(file->mode, st.st_mode, exists);
901         }
902
903         if (S_ISDIR(file->mode)) {
904                 /* The file to be received is a directory, so we need
905                  * to prepare appropriately.  If there is already a
906                  * file of that name and it is *not* a directory, then
907                  * we need to delete it.  If it doesn't exist, then
908                  * (perhaps recursively) create it. */
909                 if (statret == 0 && !S_ISDIR(st.st_mode)) {
910                         if (delete_item(fname, st.st_mode, del_opts) < 0)
911                                 return;
912                         statret = -1;
913                 }
914                 if (dry_run && statret != 0 && missing_below < 0) {
915                         missing_below = file->dir.depth;
916                         dry_run++;
917                 }
918                 if (itemizing && f_out != -1) {
919                         itemize(file, ndx, statret, &st,
920                                 statret ? ITEM_LOCAL_CHANGE : 0, 0, NULL);
921                 }
922                 if (statret != 0 && do_mkdir(fname,file->mode) < 0 && errno != EEXIST) {
923                         if (!relative_paths || errno != ENOENT
924                             || create_directory_path(fname) < 0
925                             || (do_mkdir(fname, file->mode) < 0 && errno != EEXIST)) {
926                                 rsyserr(FERROR, errno,
927                                         "recv_generator: mkdir %s failed",
928                                         full_fname(fname));
929                         }
930                 }
931                 if (set_file_attrs(fname, file, statret ? NULL : &st, 0)
932                     && verbose && code && f_out != -1)
933                         rprintf(code, "%s/\n", fname);
934                 if (delete_during && f_out != -1 && !phase && dry_run < 2
935                     && (file->flags & FLAG_DEL_HERE))
936                         delete_in_dir(the_file_list, fname, file, &st);
937                 return;
938         }
939
940         if (preserve_hard_links && file->link_u.links
941             && hard_link_check(file, ndx, fname, statret, &st,
942                                itemizing, code, HL_CHECK_MASTER))
943                 return;
944
945         if (preserve_links && S_ISLNK(file->mode)) {
946 #ifdef SUPPORT_LINKS
947                 if (safe_symlinks && unsafe_symlink(file->u.link, fname)) {
948                         if (verbose) {
949                                 if (the_file_list->count == 1)
950                                         fname = f_name(file, NULL);
951                                 rprintf(FINFO,
952                                         "ignoring unsafe symlink %s -> \"%s\"\n",
953                                         full_fname(fname), file->u.link);
954                         }
955                         return;
956                 }
957                 if (statret == 0) {
958                         char lnk[MAXPATHLEN];
959                         int len;
960
961                         if (!S_ISDIR(st.st_mode)
962                             && (len = readlink(fname, lnk, MAXPATHLEN-1)) > 0) {
963                                 lnk[len] = 0;
964                                 /* A link already pointing to the
965                                  * right place -- no further action
966                                  * required. */
967                                 if (strcmp(lnk, file->u.link) == 0) {
968                                         if (itemizing) {
969                                                 itemize(file, ndx, 0, &st, 0,
970                                                         0, NULL);
971                                         }
972                                         set_file_attrs(fname, file, &st,
973                                                        maybe_ATTRS_REPORT);
974                                         if (preserve_hard_links
975                                             && file->link_u.links) {
976                                                 hard_link_cluster(file, ndx,
977                                                                   itemizing,
978                                                                   code);
979                                         }
980                                         return;
981                                 }
982                         }
983                         /* Not the right symlink (or not a symlink), so
984                          * delete it. */
985                         if (delete_item(fname, st.st_mode, del_opts) < 0)
986                                 return;
987                         if (!S_ISLNK(st.st_mode))
988                                 statret = -1;
989                 } else if (basis_dir[0] != NULL) {
990                         if (try_dests_non(file, fname, ndx, itemizing,
991                                           maybe_ATTRS_REPORT, code) == -2) {
992 #ifndef CAN_HARDLINK_SYMLINK
993                                 if (link_dest) {
994                                         /* Resort to --copy-dest behavior. */
995                                 } else
996 #endif
997                                 if (!copy_dest)
998                                         return;
999                                 itemizing = code = 0;
1000                         }
1001                 }
1002                 if (preserve_hard_links && file->link_u.links
1003                     && hard_link_check(file, ndx, fname, -1, &st,
1004                                        itemizing, code, HL_SKIP))
1005                         return;
1006                 if (do_symlink(file->u.link,fname) != 0) {
1007                         rsyserr(FERROR, errno, "symlink %s -> \"%s\" failed",
1008                                 full_fname(fname), file->u.link);
1009                 } else {
1010                         set_file_attrs(fname, file, NULL, 0);
1011                         if (itemizing) {
1012                                 itemize(file, ndx, statret, &st,
1013                                         ITEM_LOCAL_CHANGE, 0, NULL);
1014                         }
1015                         if (code && verbose) {
1016                                 rprintf(code, "%s -> %s\n", fname,
1017                                         file->u.link);
1018                         }
1019                         if (remove_sent_files && !dry_run) {
1020                                 char numbuf[4];
1021                                 SIVAL(numbuf, 0, ndx);
1022                                 send_msg(MSG_SUCCESS, numbuf, 4);
1023                         }
1024                         if (preserve_hard_links && file->link_u.links)
1025                                 hard_link_cluster(file, ndx, itemizing, code);
1026                 }
1027 #endif
1028                 return;
1029         }
1030
1031         if ((am_root && preserve_devices && IS_DEVICE(file->mode))
1032          || (preserve_specials && IS_SPECIAL(file->mode))) {
1033                 if (statret != 0 && basis_dir[0] != NULL) {
1034                         if (try_dests_non(file, fname, ndx, itemizing,
1035                                           maybe_ATTRS_REPORT, code) == -2) {
1036 #ifndef CAN_HARDLINK_SPECIAL
1037                                 if (link_dest) {
1038                                         /* Resort to --copy-dest behavior. */
1039                                 } else
1040 #endif
1041                                 if (!copy_dest)
1042                                         return;
1043                                 itemizing = code = 0;
1044                         }
1045                 }
1046                 if (statret != 0
1047                  || (st.st_mode & ~CHMOD_BITS) != (file->mode & ~CHMOD_BITS)
1048                  || st.st_rdev != file->u.rdev) {
1049                         if (statret == 0
1050                          && delete_item(fname, st.st_mode, del_opts) < 0)
1051                                 return;
1052                         if (preserve_hard_links && file->link_u.links
1053                             && hard_link_check(file, ndx, fname, -1, &st,
1054                                                itemizing, code, HL_SKIP))
1055                                 return;
1056                         if ((IS_DEVICE(file->mode) && !IS_DEVICE(st.st_mode))
1057                          || (IS_SPECIAL(file->mode) && !IS_SPECIAL(st.st_mode)))
1058                                 statret = -1;
1059                         if (verbose > 2) {
1060                                 rprintf(FINFO,"mknod(%s,0%o,0x%x)\n",
1061                                         fname,
1062                                         (int)file->mode, (int)file->u.rdev);
1063                         }
1064                         if (do_mknod(fname,file->mode,file->u.rdev) < 0) {
1065                                 rsyserr(FERROR, errno, "mknod %s failed",
1066                                         full_fname(fname));
1067                         } else {
1068                                 set_file_attrs(fname, file, NULL, 0);
1069                                 if (itemizing) {
1070                                         itemize(file, ndx, statret, &st,
1071                                                 ITEM_LOCAL_CHANGE, 0, NULL);
1072                                 }
1073                                 if (code && verbose)
1074                                         rprintf(code, "%s\n", fname);
1075                                 if (preserve_hard_links && file->link_u.links) {
1076                                         hard_link_cluster(file, ndx,
1077                                                           itemizing, code);
1078                                 }
1079                         }
1080                 } else {
1081                         if (itemizing)
1082                                 itemize(file, ndx, statret, &st, 0, 0, NULL);
1083                         set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1084                         if (preserve_hard_links && file->link_u.links)
1085                                 hard_link_cluster(file, ndx, itemizing, code);
1086                 }
1087                 return;
1088         }
1089
1090         if (!S_ISREG(file->mode)) {
1091                 if (the_file_list->count == 1)
1092                         fname = f_name(file, NULL);
1093                 rprintf(FINFO, "skipping non-regular file \"%s\"\n", fname);
1094                 return;
1095         }
1096
1097         if (max_size && file->length > max_size) {
1098                 if (verbose > 1) {
1099                         if (the_file_list->count == 1)
1100                                 fname = f_name(file, NULL);
1101                         rprintf(FINFO, "%s is over max-size\n", fname);
1102                 }
1103                 return;
1104         }
1105         if (min_size && file->length < min_size) {
1106                 if (verbose > 1) {
1107                         if (the_file_list->count == 1)
1108                                 fname = f_name(file, NULL);
1109                         rprintf(FINFO, "%s is under min-size\n", fname);
1110                 }
1111                 return;
1112         }
1113
1114         if (ignore_existing && statret == 0) {
1115                 if (verbose > 1)
1116                         rprintf(FINFO, "%s exists\n", fname);
1117                 return;
1118         }
1119
1120         if (update_only && statret == 0
1121             && cmp_time(st.st_mtime, file->modtime) > 0) {
1122                 if (verbose > 1)
1123                         rprintf(FINFO, "%s is newer\n", fname);
1124                 return;
1125         }
1126
1127         fnamecmp = fname;
1128         fnamecmp_type = FNAMECMP_FNAME;
1129
1130         if (statret == 0 && !S_ISREG(st.st_mode)) {
1131                 if (delete_item(fname, st.st_mode, del_opts) != 0)
1132                         return;
1133                 statret = -1;
1134                 stat_errno = ENOENT;
1135         }
1136
1137         if (statret != 0 && basis_dir[0] != NULL) {
1138                 int j = try_dests_reg(file, fname, ndx, fnamecmpbuf, &st,
1139                                       itemizing, maybe_ATTRS_REPORT, code);
1140                 if (j == -2)
1141                         return;
1142                 if (j != -1) {
1143                         fnamecmp = fnamecmpbuf;
1144                         fnamecmp_type = j;
1145                         statret = 0;
1146                 }
1147         }
1148
1149         real_ret = statret;
1150         real_st = st;
1151
1152         if (partial_dir && (partialptr = partial_dir_fname(fname)) != NULL
1153             && link_stat(partialptr, &partial_st, 0) == 0
1154             && S_ISREG(partial_st.st_mode)) {
1155                 if (statret != 0)
1156                         goto prepare_to_open;
1157         } else
1158                 partialptr = NULL;
1159
1160         if (statret != 0 && fuzzy_dirlist && dry_run <= 1) {
1161                 int j = find_fuzzy(file, fuzzy_dirlist);
1162                 if (j >= 0) {
1163                         fuzzy_file = fuzzy_dirlist->files[j];
1164                         f_name(fuzzy_file, fnamecmpbuf);
1165                         if (verbose > 2) {
1166                                 rprintf(FINFO, "fuzzy basis selected for %s: %s\n",
1167                                         fname, fnamecmpbuf);
1168                         }
1169                         st.st_size = fuzzy_file->length;
1170                         statret = 0;
1171                         fnamecmp = fnamecmpbuf;
1172                         fnamecmp_type = FNAMECMP_FUZZY;
1173                 }
1174         }
1175
1176         if (statret != 0) {
1177                 if (preserve_hard_links && file->link_u.links
1178                     && hard_link_check(file, ndx, fname, statret, &st,
1179                                        itemizing, code, HL_SKIP))
1180                         return;
1181                 if (stat_errno == ENOENT)
1182                         goto notify_others;
1183                 rsyserr(FERROR, stat_errno, "recv_generator: failed to stat %s",
1184                         full_fname(fname));
1185                 return;
1186         }
1187
1188         if (append_mode && st.st_size > file->length)
1189                 return;
1190
1191         if (fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
1192                 ;
1193         else if (fnamecmp_type == FNAMECMP_FUZZY)
1194                 ;
1195         else if (unchanged_file(fnamecmp, file, &st)) {
1196                 if (partialptr) {
1197                         do_unlink(partialptr);
1198                         handle_partial_dir(partialptr, PDIR_DELETE);
1199                 }
1200                 if (itemizing) {
1201                         itemize(file, ndx, real_ret, &real_st,
1202                                 0, 0, NULL);
1203                 }
1204                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1205                 if (preserve_hard_links && file->link_u.links)
1206                         hard_link_cluster(file, ndx, itemizing, code);
1207                 return;
1208         }
1209
1210   prepare_to_open:
1211         if (partialptr) {
1212                 st = partial_st;
1213                 fnamecmp = partialptr;
1214                 fnamecmp_type = FNAMECMP_PARTIAL_DIR;
1215                 statret = 0;
1216         }
1217
1218         if (!do_xfers || read_batch || whole_file)
1219                 goto notify_others;
1220
1221         if (fuzzy_dirlist) {
1222                 int j = flist_find(fuzzy_dirlist, file);
1223                 if (j >= 0) /* don't use changing file as future fuzzy basis */
1224                         fuzzy_dirlist->files[j]->flags |= FLAG_NO_FUZZY;
1225         }
1226
1227         /* open the file */
1228         fd = do_open(fnamecmp, O_RDONLY, 0);
1229
1230         if (fd == -1) {
1231                 rsyserr(FERROR, errno, "failed to open %s, continuing",
1232                         full_fname(fnamecmp));
1233           pretend_missing:
1234                 /* pretend the file didn't exist */
1235                 if (preserve_hard_links && file->link_u.links
1236                     && hard_link_check(file, ndx, fname, statret, &st,
1237                                        itemizing, code, HL_SKIP))
1238                         return;
1239                 statret = real_ret = -1;
1240                 goto notify_others;
1241         }
1242
1243         if (inplace && make_backups && fnamecmp_type == FNAMECMP_FNAME) {
1244                 if (!(backupptr = get_backup_name(fname))) {
1245                         close(fd);
1246                         return;
1247                 }
1248                 if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) {
1249                         close(fd);
1250                         goto pretend_missing;
1251                 }
1252                 if (robust_unlink(backupptr) && errno != ENOENT) {
1253                         rsyserr(FERROR, errno, "unlink %s",
1254                                 full_fname(backupptr));
1255                         free(back_file);
1256                         close(fd);
1257                         return;
1258                 }
1259                 if ((f_copy = do_open(backupptr,
1260                     O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) {
1261                         rsyserr(FERROR, errno, "open %s",
1262                                 full_fname(backupptr));
1263                         free(back_file);
1264                         close(fd);
1265                         return;
1266                 }
1267                 fnamecmp_type = FNAMECMP_BACKUP;
1268         }
1269
1270         if (verbose > 3) {
1271                 rprintf(FINFO, "gen mapped %s of size %.0f\n",
1272                         fnamecmp, (double)st.st_size);
1273         }
1274
1275         if (verbose > 2)
1276                 rprintf(FINFO, "generating and sending sums for %d\n", ndx);
1277
1278   notify_others:
1279         if (remove_sent_files && !delay_updates && !phase)
1280             increment_active_files(ndx, itemizing, code);
1281         write_int(f_out, ndx);
1282         if (itemizing) {
1283                 int iflags = ITEM_TRANSFER;
1284                 if (always_checksum)
1285                         iflags |= ITEM_REPORT_CHECKSUM;
1286                 if (fnamecmp_type != FNAMECMP_FNAME)
1287                         iflags |= ITEM_BASIS_TYPE_FOLLOWS;
1288                 if (fnamecmp_type == FNAMECMP_FUZZY)
1289                         iflags |= ITEM_XNAME_FOLLOWS;
1290                 itemize(file, -1, real_ret, &real_st, iflags, fnamecmp_type,
1291                         fuzzy_file ? fuzzy_file->basename : NULL);
1292         }
1293
1294         if (!do_xfers) {
1295                 if (preserve_hard_links && file->link_u.links)
1296                         hard_link_cluster(file, ndx, itemizing, code);
1297                 return;
1298         }
1299         if (read_batch)
1300                 return;
1301
1302         if (statret != 0 || whole_file) {
1303                 write_sum_head(f_out, NULL);
1304                 return;
1305         }
1306
1307         generate_and_send_sums(fd, st.st_size, f_out, f_copy);
1308
1309         if (f_copy >= 0) {
1310                 close(f_copy);
1311                 set_file_attrs(backupptr, back_file, NULL, 0);
1312                 if (verbose > 1) {
1313                         rprintf(FINFO, "backed up %s to %s\n",
1314                                 fname, backupptr);
1315                 }
1316                 free(back_file);
1317         }
1318
1319         close(fd);
1320 }
1321
1322 void generate_files(int f_out, struct file_list *flist, char *local_name)
1323 {
1324         int i;
1325         char fbuf[MAXPATHLEN];
1326         int itemizing, maybe_ATTRS_REPORT;
1327         enum logcode code;
1328         int lull_mod = allowed_lull * 5;
1329         int need_retouch_dir_times = preserve_times && !omit_dir_times;
1330         int need_retouch_dir_perms = 0;
1331         int save_ignore_existing = ignore_existing;
1332         int save_ignore_non_existing = ignore_non_existing;
1333         int save_do_progress = do_progress;
1334         int save_make_backups = make_backups;
1335         int dir_tweaking = !(list_only || local_name || dry_run);
1336
1337         if (protocol_version >= 29) {
1338                 itemizing = 1;
1339                 maybe_ATTRS_REPORT = log_format_has_i ? 0 : ATTRS_REPORT;
1340                 code = logfile_format_has_i ? 0 : FLOG;
1341         } else if (am_daemon) {
1342                 itemizing = logfile_format_has_i && do_xfers;
1343                 maybe_ATTRS_REPORT = ATTRS_REPORT;
1344                 code = itemizing || !do_xfers ? FCLIENT : FINFO;
1345         } else if (!am_server) {
1346                 itemizing = log_format_has_i;
1347                 maybe_ATTRS_REPORT = log_format_has_i ? 0 : ATTRS_REPORT;
1348                 code = itemizing ? 0 : FINFO;
1349         } else {
1350                 itemizing = 0;
1351                 maybe_ATTRS_REPORT = ATTRS_REPORT;
1352                 code = FINFO;
1353         }
1354
1355         if (verbose > 2) {
1356                 rprintf(FINFO, "generator starting pid=%ld count=%d\n",
1357                         (long)getpid(), flist->count);
1358         }
1359
1360         if (delete_before && !local_name && flist->count > 0)
1361                 do_delete_pass(flist);
1362         do_progress = 0;
1363
1364         if (append_mode || whole_file < 0)
1365                 whole_file = 0;
1366         if (verbose >= 2) {
1367                 rprintf(FINFO, "delta-transmission %s\n",
1368                         whole_file
1369                         ? "disabled for local transfer or --whole-file"
1370                         : "enabled");
1371         }
1372
1373         /* Since we often fill up the outgoing socket and then just sit around
1374          * waiting for the other 2 processes to do their thing, we don't want
1375          * to exit on a timeout.  If the data stops flowing, the receiver will
1376          * notice that and let us know via the redo pipe (or its closing). */
1377         ignore_timeout = 1;
1378
1379         for (i = 0; i < flist->count; i++) {
1380                 struct file_struct *file = flist->files[i];
1381
1382                 if (!file->basename)
1383                         continue;
1384
1385                 if (local_name)
1386                         strlcpy(fbuf, local_name, sizeof fbuf);
1387                 else
1388                         f_name(file, fbuf);
1389                 recv_generator(fbuf, file, i, itemizing, maybe_ATTRS_REPORT,
1390                                code, f_out);
1391
1392                 /* We need to ensure that any dirs we create have writeable
1393                  * permissions during the time we are putting files within
1394                  * them.  This is then fixed after the transfer is done. */
1395 #ifdef HAVE_CHMOD
1396                 if (!am_root && S_ISDIR(file->mode) && !(file->mode & S_IWUSR)
1397                  && dir_tweaking) {
1398                         mode_t mode = file->mode | S_IWUSR; /* user write */
1399                         char *fname = local_name ? local_name : fbuf;
1400                         if (do_chmod(fname, mode) < 0) {
1401                                 rsyserr(FERROR, errno,
1402                                         "failed to modify permissions on %s",
1403                                         full_fname(fname));
1404                         }
1405                         need_retouch_dir_perms = 1;
1406                 }
1407 #endif
1408
1409                 if (preserve_hard_links)
1410                         check_for_finished_hlinks(itemizing, code);
1411
1412                 if (allowed_lull && !(i % lull_mod))
1413                         maybe_send_keepalive();
1414                 else if (!(i % 200))
1415                         maybe_flush_socket();
1416         }
1417         recv_generator(NULL, NULL, 0, 0, 0, code, -1);
1418         if (delete_during)
1419                 delete_in_dir(NULL, NULL, NULL, NULL);
1420
1421         phase++;
1422         csum_length = SUM_LENGTH;
1423         max_size = min_size = ignore_existing = ignore_non_existing = 0;
1424         update_only = always_checksum = size_only = 0;
1425         ignore_times = 1;
1426         if (append_mode)  /* resend w/o append mode */
1427                 append_mode = -1; /* ... but only longer files */
1428         make_backups = 0; /* avoid a duplicate backup for inplace processing */
1429
1430         if (verbose > 2)
1431                 rprintf(FINFO,"generate_files phase=%d\n",phase);
1432
1433         write_int(f_out, -1);
1434
1435         /* files can cycle through the system more than once
1436          * to catch initial checksum errors */
1437         while ((i = get_redo_num(itemizing, code)) != -1) {
1438                 struct file_struct *file = flist->files[i];
1439                 if (local_name)
1440                         strlcpy(fbuf, local_name, sizeof fbuf);
1441                 else
1442                         f_name(file, fbuf);
1443                 recv_generator(fbuf, file, i, itemizing, maybe_ATTRS_REPORT,
1444                                code, f_out);
1445         }
1446
1447         phase++;
1448         ignore_non_existing = save_ignore_non_existing;
1449         ignore_existing = save_ignore_existing;
1450         make_backups = save_make_backups;
1451
1452         if (verbose > 2)
1453                 rprintf(FINFO,"generate_files phase=%d\n",phase);
1454
1455         write_int(f_out, -1);
1456         /* Reduce round-trip lag-time for a useless delay-updates phase. */
1457         if (protocol_version >= 29 && !delay_updates)
1458                 write_int(f_out, -1);
1459
1460         /* Read MSG_DONE for the redo phase (and any prior messages). */
1461         get_redo_num(itemizing, code);
1462
1463         if (protocol_version >= 29) {
1464                 phase++;
1465                 if (verbose > 2)
1466                         rprintf(FINFO, "generate_files phase=%d\n", phase);
1467                 if (delay_updates)
1468                         write_int(f_out, -1);
1469                 /* Read MSG_DONE for delay-updates phase & prior messages. */
1470                 get_redo_num(itemizing, code);
1471         }
1472
1473         do_progress = save_do_progress;
1474         if (delete_after && !local_name && flist->count > 0)
1475                 do_delete_pass(flist);
1476
1477         if ((need_retouch_dir_perms || need_retouch_dir_times) && dir_tweaking) {
1478                 int j = 0;
1479                 /* Now we need to fix any directory permissions that were
1480                  * modified during the transfer and/or re-set any tweaked
1481                  * modified-time values. */
1482                 for (i = 0; i < flist->count; i++) {
1483                         struct file_struct *file = flist->files[i];
1484
1485                         if (!file->basename || !S_ISDIR(file->mode))
1486                                 continue;
1487                         if (!need_retouch_dir_times && file->mode & S_IWUSR)
1488                                 continue;
1489                         recv_generator(f_name(file, NULL), file, i, itemizing,
1490                                        maybe_ATTRS_REPORT, code, -1);
1491                         if (allowed_lull && !(++j % lull_mod))
1492                                 maybe_send_keepalive();
1493                         else if (!(j % 200))
1494                                 maybe_flush_socket();
1495                 }
1496         }
1497         recv_generator(NULL, NULL, 0, 0, 0, code, -1);
1498
1499         if (max_delete > 0 && deletion_count > max_delete) {
1500                 rprintf(FINFO,
1501                         "Deletions stopped due to --max-delete limit (%d skipped)\n",
1502                         deletion_count - max_delete);
1503                 io_error |= IOERR_DEL_LIMIT;
1504         }
1505
1506         if (verbose > 2)
1507                 rprintf(FINFO,"generate_files finished\n");
1508 }