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