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