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