- Make some char* pointers const.
[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_DIR) {
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, F_BASENAME(fp), 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 (!F_IS_ACTIVE(fp))
395                         continue;
396                 if (fp->flags & FLAG_MOUNT_DIR) {
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_XFER_DIR))
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 != F_UID(file))
455                 return 0;
456
457         if (preserve_gid && F_GID(file) != GID_NONE && st->st_gid != F_GID(file))
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) && F_LENGTH(file) != 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 && F_UID(file) != st->st_uid)
481                         iflags |= ITEM_REPORT_OWNER;
482                 if (preserve_gid && F_GID(file) != GID_NONE
483                     && st->st_gid != F_GID(file))
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 != F_LENGTH(file))
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, F_SUM(file), 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 = F_BASENAME(file);
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) || !F_LENGTH(fp) || fp->flags & FLAG_SENT)
681                         continue;
682
683                 name = F_BASENAME(fp);
684
685                 if (F_LENGTH(fp) == F_LENGTH(file)
686                     && cmp_time(fp->modtime, file->modtime) == 0) {
687                         if (verbose > 4) {
688                                 rprintf(FINFO,
689                                         "fuzzy size/modtime match for %s\n",
690                                         name);
691                         }
692                         return j;
693                 }
694
695                 len = strlen(name);
696                 suf = find_filename_suffix(name, len, &suf_len);
697
698                 dist = fuzzy_distance(name, len, fname, fname_len);
699                 /* Add some extra weight to how well the suffixes match. */
700                 dist += fuzzy_distance(suf, suf_len, fname_suf, fname_suf_len)
701                       * 10;
702                 if (verbose > 4) {
703                         rprintf(FINFO, "fuzzy distance for %s = %d.%05d\n",
704                                 name, (int)(dist>>16), (int)(dist&0xFFFF));
705                 }
706                 if (dist <= lowest_dist) {
707                         lowest_dist = dist;
708                         lowest_j = j;
709                 }
710         }
711
712         return lowest_j;
713 }
714
715 void check_for_finished_hlinks(int itemizing, enum logcode code)
716 {
717         struct file_struct *file;
718         int ndx;
719
720         while ((ndx = get_hlink_num()) != -1) {
721                 if (ndx < 0 || ndx >= the_file_list->count)
722                         continue;
723
724                 file = the_file_list->files[ndx];
725                 if (!F_IS_HLINKED(file))
726                         continue;
727
728                 hard_link_cluster(file, ndx, itemizing, code, -1);
729         }
730 }
731
732 /* This is only called for regular files.  We return -2 if we've finished
733  * handling the file, -1 if no dest-linking occurred, or a non-negative
734  * value if we found an alternate basis file. */
735 static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
736                          char *cmpbuf, STRUCT_STAT *stp, int itemizing,
737                          int maybe_ATTRS_REPORT, enum logcode code)
738 {
739         int best_match = -1;
740         int match_level = 0;
741         int j = 0;
742
743         do {
744                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
745                 if (link_stat(cmpbuf, stp, 0) < 0 || !S_ISREG(stp->st_mode))
746                         continue;
747                 switch (match_level) {
748                 case 0:
749                         best_match = j;
750                         match_level = 1;
751                         /* FALL THROUGH */
752                 case 1:
753                         if (!unchanged_file(cmpbuf, file, stp))
754                                 continue;
755                         best_match = j;
756                         match_level = 2;
757                         /* FALL THROUGH */
758                 case 2:
759                         if (!unchanged_attrs(file, stp))
760                                 continue;
761                         if (always_checksum && preserve_times
762                          && cmp_time(stp->st_mtime, file->modtime))
763                                 continue;
764                         best_match = j;
765                         match_level = 3;
766                         break;
767                 }
768                 break;
769         } while (basis_dir[++j] != NULL);
770
771         if (!match_level)
772                 return -1;
773
774         if (j != best_match) {
775                 j = best_match;
776                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
777                 if (link_stat(cmpbuf, stp, 0) < 0)
778                         return -1;
779         }
780
781         if (match_level == 3 && !copy_dest) {
782 #ifdef SUPPORT_HARD_LINKS
783                 if (link_dest) {
784                         int i = itemizing && (verbose > 1 || stdout_format_has_i > 1);
785                         if (hard_link_one(file, ndx, fname, 0, stp,
786                                           cmpbuf, 1, i, code) < 0)
787                                 goto try_a_copy;
788                         if (preserve_hard_links && F_IS_HLINKED(file))
789                                 hard_link_cluster(file, ndx, itemizing, code, j);
790                 } else
791 #endif
792                 if (itemizing)
793                         itemize(file, ndx, 0, stp, 0, 0, NULL);
794                 if (verbose > 1 && maybe_ATTRS_REPORT) {
795                         rprintf(FCLIENT, "%s is uptodate\n", fname);
796                 }
797                 return -2;
798         }
799
800         if (match_level >= 2) {
801           try_a_copy: /* Copy the file locally. */
802                 if (copy_file(cmpbuf, fname, file->mode) < 0) {
803                         if (verbose) {
804                                 rsyserr(FINFO, errno, "copy_file %s => %s",
805                                         full_fname(cmpbuf), fname);
806                         }
807                         return -1;
808                 }
809                 if (itemizing)
810                         itemize(file, ndx, 0, stp, ITEM_LOCAL_CHANGE, 0, NULL);
811                 set_file_attrs(fname, file, NULL, 0);
812                 if (maybe_ATTRS_REPORT
813                  && ((!itemizing && verbose && match_level == 2)
814                   || (verbose > 1 && match_level == 3))) {
815                         code = match_level == 3 ? FCLIENT : FINFO;
816                         rprintf(code, "%s%s\n", fname,
817                                 match_level == 3 ? " is uptodate" : "");
818                 }
819                 if (preserve_hard_links && F_IS_HLINKED(file))
820                         hard_link_cluster(file, ndx, itemizing, code, j);
821                 return -2;
822         }
823
824         return FNAMECMP_BASIS_DIR_LOW + j;
825 }
826
827 /* This is only called for non-regular files.  We return -2 if we've finished
828  * handling the file, or -1 if no dest-linking occurred, or a non-negative
829  * value if we found an alternate basis file. */
830 static int try_dests_non(struct file_struct *file, char *fname, int ndx,
831                          char *cmpbuf, STRUCT_STAT *stp, int itemizing,
832                          int maybe_ATTRS_REPORT, enum logcode code)
833 {
834         char lnk[MAXPATHLEN];
835         int best_match = -1;
836         int match_level = 0;
837         enum nonregtype type;
838         int len, j = 0;
839
840 #ifndef SUPPORT_LINKS
841         if (S_ISLNK(file->mode))
842                 return -1;
843 #endif
844         if (S_ISDIR(file->mode)) {
845                 type = TYPE_DIR;
846         } else if (IS_SPECIAL(file->mode))
847                 type = TYPE_SPECIAL;
848         else if (IS_DEVICE(file->mode))
849                 type = TYPE_DEVICE;
850 #ifdef SUPPORT_LINKS
851         else if (S_ISLNK(file->mode))
852                 type = TYPE_SYMLINK;
853 #endif
854         else {
855                 rprintf(FERROR,
856                         "internal: try_dests_non() called with invalid mode (%o)\n",
857                         (int)file->mode);
858                 exit_cleanup(RERR_UNSUPPORTED);
859         }
860
861         do {
862                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
863                 if (link_stat(cmpbuf, stp, 0) < 0)
864                         continue;
865                 switch (type) {
866                 case TYPE_DIR:
867                         if (!S_ISDIR(stp->st_mode))
868                                 continue;
869                         break;
870                 case TYPE_SPECIAL:
871                         if (!IS_SPECIAL(stp->st_mode))
872                                 continue;
873                         break;
874                 case TYPE_DEVICE:
875                         if (!IS_DEVICE(stp->st_mode))
876                                 continue;
877                         break;
878 #ifdef SUPPORT_LINKS
879                 case TYPE_SYMLINK:
880                         if (!S_ISLNK(stp->st_mode))
881                                 continue;
882                         break;
883 #endif
884                 }
885                 if (match_level < 1) {
886                         match_level = 1;
887                         best_match = j;
888                 }
889                 switch (type) {
890                 case TYPE_DIR:
891                         break;
892                 case TYPE_SPECIAL:
893                 case TYPE_DEVICE:
894                         if (stp->st_rdev != MAKEDEV(F_DMAJOR(file), F_DMINOR(file)))
895                                 continue;
896                         break;
897 #ifdef SUPPORT_LINKS
898                 case TYPE_SYMLINK:
899                         if ((len = readlink(cmpbuf, lnk, MAXPATHLEN-1)) <= 0)
900                                 continue;
901                         lnk[len] = '\0';
902                         if (strcmp(lnk, F_SYMLINK(file)) != 0)
903                                 continue;
904                         break;
905 #endif
906                 }
907                 if (match_level < 2) {
908                         match_level = 2;
909                         best_match = j;
910                 }
911                 if (unchanged_attrs(file, stp)) {
912                         match_level = 3;
913                         best_match = j;
914                         break;
915                 }
916         } while (basis_dir[++j] != NULL);
917
918         if (!match_level)
919                 return -1;
920
921         if (j != best_match) {
922                 j = best_match;
923                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
924                 if (link_stat(cmpbuf, stp, 0) < 0)
925                         return -1;
926         }
927
928         if (match_level == 3) {
929 #ifdef SUPPORT_HARD_LINKS
930                 if (link_dest
931 #ifndef CAN_HARDLINK_SYMLINK
932                  && !S_ISLNK(file->mode)
933 #endif
934 #ifndef CAN_HARDLINK_SPECIAL
935                  && !IS_SPECIAL(file->mode) && !IS_DEVICE(file->mode)
936 #endif
937                  && !S_ISDIR(file->mode)) {
938                         if (do_link(cmpbuf, fname) < 0) {
939                                 rsyserr(FERROR, errno,
940                                         "failed to hard-link %s with %s",
941                                         cmpbuf, fname);
942                                 return j;
943                         }
944                         if (preserve_hard_links && F_IS_HLINKED(file))
945                                 hard_link_cluster(file, ndx, itemizing, code, -1);
946                 } else
947 #endif
948                         match_level = 2;
949                 if (itemizing && stdout_format_has_i
950                  && (verbose > 1 || stdout_format_has_i > 1)) {
951                         int chg = compare_dest && type != TYPE_DIR ? 0
952                             : ITEM_LOCAL_CHANGE
953                              + (match_level == 3 ? ITEM_XNAME_FOLLOWS : 0);
954                         char *lp = match_level == 3 ? "" : NULL;
955                         itemize(file, ndx, 0, stp, chg + ITEM_MATCHED, 0, lp);
956                 }
957                 if (verbose > 1 && maybe_ATTRS_REPORT) {
958                         rprintf(FCLIENT, "%s%s is uptodate\n",
959                                 fname, type == TYPE_DIR ? "/" : "");
960                 }
961                 return -2;
962         }
963
964         return j;
965 }
966
967 static int phase = 0;
968
969 /* Acts on the_file_list->file's ndx'th item, whose name is fname.  If a dir,
970  * make sure it exists, and has the right permissions/timestamp info.  For
971  * all other non-regular files (symlinks, etc.) we create them here.  For
972  * regular files that have changed, we try to find a basis file and then
973  * start sending checksums.
974  *
975  * When fname is non-null, it must point to a MAXPATHLEN buffer!
976  *
977  * Note that f_out is set to -1 when doing final directory-permission and
978  * modification-time repair. */
979 static void recv_generator(char *fname, struct file_struct *file, int ndx,
980                            int itemizing, int maybe_ATTRS_REPORT,
981                            enum logcode code, int f_out)
982 {
983         static int missing_below = -1, excluded_below = -1;
984         static const char *parent_dirname = "";
985         static struct file_list *fuzzy_dirlist = NULL;
986         static int need_fuzzy_dirlist = 0;
987         struct file_struct *fuzzy_file = NULL;
988         int fd = -1, f_copy = -1;
989         STRUCT_STAT st, real_st, partial_st;
990         struct file_struct *back_file = NULL;
991         int statret, real_ret, stat_errno;
992         char *fnamecmp, *partialptr, *backupptr = NULL;
993         char fnamecmpbuf[MAXPATHLEN];
994         uchar fnamecmp_type;
995         int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0;
996
997         if (list_only)
998                 return;
999
1000         if (!fname) {
1001                 if (fuzzy_dirlist) {
1002                         flist_free(fuzzy_dirlist);
1003                         fuzzy_dirlist = NULL;
1004                 }
1005                 if (missing_below >= 0) {
1006                         if (dry_run)
1007                                 dry_run--;
1008                         missing_below = -1;
1009                 }
1010                 parent_dirname = "";
1011                 return;
1012         }
1013
1014         if (verbose > 2)
1015                 rprintf(FINFO, "recv_generator(%s,%d)\n", fname, ndx);
1016
1017         if (server_filter_list.head) {
1018                 if (excluded_below >= 0) {
1019                         if (file->dir.depth > excluded_below)
1020                                 goto skipping;
1021                         excluded_below = -1;
1022                 }
1023                 if (check_filter(&server_filter_list, fname,
1024                                  S_ISDIR(file->mode)) < 0) {
1025                         if (S_ISDIR(file->mode))
1026                                 excluded_below = file->dir.depth;
1027                   skipping:
1028                         if (verbose) {
1029                                 rprintf(FINFO,
1030                                         "skipping server-excluded file \"%s\"\n",
1031                                         fname);
1032                         }
1033                         return;
1034                 }
1035         }
1036
1037         if (missing_below >= 0) {
1038                 if (file->dir.depth <= missing_below) {
1039                         if (dry_run)
1040                                 dry_run--;
1041                         missing_below = -1;
1042                 } else if (!dry_run)
1043                         return;
1044         }
1045         if (dry_run > 1) {
1046                 statret = -1;
1047                 stat_errno = ENOENT;
1048         } else {
1049                 const char *dn = file->dirname ? file->dirname : ".";
1050                 if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) {
1051                         if (relative_paths && !implied_dirs
1052                          && do_stat(dn, &st) < 0
1053                          && create_directory_path(fname) < 0) {
1054                                 rsyserr(FERROR, errno,
1055                                         "recv_generator: mkdir %s failed",
1056                                         full_fname(dn));
1057                         }
1058                         if (fuzzy_dirlist) {
1059                                 flist_free(fuzzy_dirlist);
1060                                 fuzzy_dirlist = NULL;
1061                         }
1062                         if (fuzzy_basis)
1063                                 need_fuzzy_dirlist = 1;
1064                 }
1065                 parent_dirname = dn;
1066
1067                 if (need_fuzzy_dirlist && S_ISREG(file->mode)) {
1068                         strlcpy(fnamecmpbuf, dn, sizeof fnamecmpbuf);
1069                         fuzzy_dirlist = get_dirlist(fnamecmpbuf, -1, 1);
1070                         need_fuzzy_dirlist = 0;
1071                 }
1072
1073                 statret = link_stat(fname, &st,
1074                                     keep_dirlinks && S_ISDIR(file->mode));
1075                 stat_errno = errno;
1076         }
1077
1078         if (ignore_non_existing && statret == -1 && stat_errno == ENOENT) {
1079                 if (verbose > 1) {
1080                         rprintf(FINFO, "not creating new %s \"%s\"\n",
1081                                 S_ISDIR(file->mode) ? "directory" : "file",
1082                                 fname);
1083                 }
1084                 return;
1085         }
1086
1087         /* If we're not preserving permissions, change the file-list's
1088          * mode based on the local permissions and some heuristics. */
1089         if (!preserve_perms) {
1090                 int exists = statret == 0
1091                           && S_ISDIR(st.st_mode) == S_ISDIR(file->mode);
1092                 file->mode = dest_mode(file->mode, st.st_mode, exists);
1093         }
1094
1095         if (S_ISDIR(file->mode)) {
1096                 /* The file to be received is a directory, so we need
1097                  * to prepare appropriately.  If there is already a
1098                  * file of that name and it is *not* a directory, then
1099                  * we need to delete it.  If it doesn't exist, then
1100                  * (perhaps recursively) create it. */
1101                 if (statret == 0 && !S_ISDIR(st.st_mode)) {
1102                         if (delete_item(fname, st.st_mode, "directory", del_opts) != 0)
1103                                 return;
1104                         statret = -1;
1105                 }
1106                 if (dry_run && statret != 0 && missing_below < 0) {
1107                         missing_below = file->dir.depth;
1108                         dry_run++;
1109                 }
1110                 real_ret = statret;
1111                 real_st = st;
1112                 if (new_root_dir) {
1113                         if (*fname == '.' && fname[1] == '\0')
1114                                 statret = -1;
1115                         new_root_dir = 0;
1116                 }
1117                 if (statret != 0 && basis_dir[0] != NULL) {
1118                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &st,
1119                                               itemizing, maybe_ATTRS_REPORT, code);
1120                         if (j == -2) {
1121                                 itemizing = 0;
1122                                 code = FNONE;
1123                         } else if (j >= 0)
1124                                 statret = 1;
1125                 }
1126                 if (itemizing && f_out != -1) {
1127                         itemize(file, ndx, statret, &st,
1128                                 statret ? ITEM_LOCAL_CHANGE : 0, 0, NULL);
1129                 }
1130                 if (real_ret != 0 && do_mkdir(fname,file->mode) < 0 && errno != EEXIST) {
1131                         if (!relative_paths || errno != ENOENT
1132                             || create_directory_path(fname) < 0
1133                             || (do_mkdir(fname, file->mode) < 0 && errno != EEXIST)) {
1134                                 rsyserr(FERROR, errno,
1135                                         "recv_generator: mkdir %s failed",
1136                                         full_fname(fname));
1137                                 file->flags |= FLAG_MISSING_DIR;
1138                                 if (ndx+1 < the_file_list->count
1139                                  && the_file_list->files[ndx+1]->dir.depth > file->dir.depth) {
1140                                         rprintf(FERROR,
1141                                             "*** Skipping everything below this failed directory ***\n");
1142                                         missing_below = file->dir.depth;
1143                                 }
1144                                 return;
1145                         }
1146                 }
1147                 if (set_file_attrs(fname, file, real_ret ? NULL : &real_st, 0)
1148                     && verbose && code != FNONE && f_out != -1)
1149                         rprintf(code, "%s/\n", fname);
1150                 if (real_ret != 0 && one_file_system)
1151                         real_st.st_dev = filesystem_dev;
1152                 if (delete_during && f_out != -1 && !phase && dry_run < 2
1153                     && (file->flags & FLAG_XFER_DIR))
1154                         delete_in_dir(the_file_list, fname, file, &real_st);
1155                 return;
1156         }
1157
1158         if (preserve_hard_links && F_IS_HLINKED(file)
1159             && hard_link_check(file, ndx, fname, statret, &st,
1160                                itemizing, code, HL_CHECK_MASTER))
1161                 return;
1162
1163         if (preserve_links && S_ISLNK(file->mode)) {
1164 #ifdef SUPPORT_LINKS
1165                 const char *sl = F_SYMLINK(file);
1166                 if (safe_symlinks && unsafe_symlink(sl, fname)) {
1167                         if (verbose) {
1168                                 if (the_file_list->count == 1)
1169                                         fname = f_name(file, NULL);
1170                                 rprintf(FINFO,
1171                                         "ignoring unsafe symlink %s -> \"%s\"\n",
1172                                         full_fname(fname), sl);
1173                         }
1174                         return;
1175                 }
1176                 if (statret == 0) {
1177                         char lnk[MAXPATHLEN];
1178                         int len;
1179
1180                         if (!S_ISLNK(st.st_mode))
1181                                 statret = -1;
1182                         else if ((len = readlink(fname, lnk, MAXPATHLEN-1)) > 0
1183                               && strncmp(lnk, sl, len) == 0 && sl[len] == '\0') {
1184                                 /* The link is pointing to the right place. */
1185                                 if (itemizing)
1186                                         itemize(file, ndx, 0, &st, 0, 0, NULL);
1187                                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1188                                 if (preserve_hard_links && F_IS_HLINKED(file))
1189                                         hard_link_cluster(file, ndx, itemizing, code, -1);
1190                                 if (remove_source_files == 1)
1191                                         goto return_with_success;
1192                                 return;
1193                         }
1194                         /* Not the right symlink (or not a symlink), so
1195                          * delete it. */
1196                         if (delete_item(fname, st.st_mode, "symlink", del_opts) != 0)
1197                                 return;
1198                 } else if (basis_dir[0] != NULL) {
1199                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &st,
1200                                               itemizing, maybe_ATTRS_REPORT, code);
1201                         if (j == -2) {
1202 #ifndef CAN_HARDLINK_SYMLINK
1203                                 if (link_dest) {
1204                                         /* Resort to --copy-dest behavior. */
1205                                 } else
1206 #endif
1207                                 if (!copy_dest)
1208                                         return;
1209                                 itemizing = 0;
1210                                 code = FNONE;
1211                         } else if (j >= 0)
1212                                 statret = 1;
1213                 }
1214                 if (preserve_hard_links && F_IS_HLINKED(file)
1215                     && hard_link_check(file, ndx, fname, -1, &st,
1216                                        itemizing, code, HL_SKIP))
1217                         return;
1218                 if (do_symlink(sl, fname) != 0) {
1219                         rsyserr(FERROR, errno, "symlink %s -> \"%s\" failed",
1220                                 full_fname(fname), sl);
1221                 } else {
1222                         set_file_attrs(fname, file, NULL, 0);
1223                         if (itemizing) {
1224                                 itemize(file, ndx, statret, &st,
1225                                         ITEM_LOCAL_CHANGE, 0, NULL);
1226                         }
1227                         if (code != FNONE && verbose)
1228                                 rprintf(code, "%s -> %s\n", fname, sl);
1229                         if (preserve_hard_links && F_IS_HLINKED(file))
1230                                 hard_link_cluster(file, ndx, itemizing, code, -1);
1231                         /* This does not check remove_source_files == 1
1232                          * because this is one of the items that the old
1233                          * --remove-sent-files option would remove. */
1234                         if (remove_source_files)
1235                                 goto return_with_success;
1236                 }
1237 #endif
1238                 return;
1239         }
1240
1241         if ((am_root && preserve_devices && IS_DEVICE(file->mode))
1242          || (preserve_specials && IS_SPECIAL(file->mode))) {
1243                 dev_t rdev = MAKEDEV(F_DMAJOR(file), F_DMINOR(file));
1244                 if (statret == 0) {
1245                         char *t;
1246                         if (IS_DEVICE(file->mode)) {
1247                                 if (!IS_DEVICE(st.st_mode))
1248                                         statret = -1;
1249                                 t = "device file";
1250                         } else {
1251                                 if (!IS_SPECIAL(st.st_mode))
1252                                         statret = -1;
1253                                 t = "special file";
1254                         }
1255                         if (statret == 0
1256                          && (st.st_mode & ~CHMOD_BITS) == (file->mode & ~CHMOD_BITS)
1257                          && st.st_rdev == rdev) {
1258                                 /* The device or special file is identical. */
1259                                 if (itemizing)
1260                                         itemize(file, ndx, 0, &st, 0, 0, NULL);
1261                                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1262                                 if (preserve_hard_links && F_IS_HLINKED(file))
1263                                         hard_link_cluster(file, ndx, itemizing, code, -1);
1264                                 if (remove_source_files == 1)
1265                                         goto return_with_success;
1266                                 return;
1267                         }
1268                         if (delete_item(fname, st.st_mode, t, del_opts) != 0)
1269                                 return;
1270                 } else if (basis_dir[0] != NULL) {
1271                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &st,
1272                                               itemizing, maybe_ATTRS_REPORT, code);
1273                         if (j == -2) {
1274 #ifndef CAN_HARDLINK_SPECIAL
1275                                 if (link_dest) {
1276                                         /* Resort to --copy-dest behavior. */
1277                                 } else
1278 #endif
1279                                 if (!copy_dest)
1280                                         return;
1281                                 itemizing = 0;
1282                                 code = FNONE;
1283                         } else if (j >= 0)
1284                                 statret = 1;
1285                 }
1286                 if (preserve_hard_links && F_IS_HLINKED(file)
1287                     && hard_link_check(file, ndx, fname, -1, &st,
1288                                        itemizing, code, HL_SKIP))
1289                         return;
1290                 if (verbose > 2) {
1291                         rprintf(FINFO,"mknod(%s,0%o,0x%x)\n",
1292                                 fname, (int)file->mode, (int)rdev);
1293                 }
1294                 if (do_mknod(fname, file->mode, rdev) < 0) {
1295                         rsyserr(FERROR, errno, "mknod %s failed",
1296                                 full_fname(fname));
1297                 } else {
1298                         set_file_attrs(fname, file, NULL, 0);
1299                         if (itemizing) {
1300                                 itemize(file, ndx, statret, &st,
1301                                         ITEM_LOCAL_CHANGE, 0, NULL);
1302                         }
1303                         if (code != FNONE && verbose)
1304                                 rprintf(code, "%s\n", fname);
1305                         if (preserve_hard_links && F_IS_HLINKED(file))
1306                                 hard_link_cluster(file, ndx, itemizing, code, -1);
1307                         if (remove_source_files == 1)
1308                                 goto return_with_success;
1309                 }
1310                 return;
1311         }
1312
1313         if (!S_ISREG(file->mode)) {
1314                 if (the_file_list->count == 1)
1315                         fname = f_name(file, NULL);
1316                 rprintf(FINFO, "skipping non-regular file \"%s\"\n", fname);
1317                 return;
1318         }
1319
1320         if (max_size && F_LENGTH(file) > max_size) {
1321                 if (verbose > 1) {
1322                         if (the_file_list->count == 1)
1323                                 fname = f_name(file, NULL);
1324                         rprintf(FINFO, "%s is over max-size\n", fname);
1325                 }
1326                 return;
1327         }
1328         if (min_size && F_LENGTH(file) < min_size) {
1329                 if (verbose > 1) {
1330                         if (the_file_list->count == 1)
1331                                 fname = f_name(file, NULL);
1332                         rprintf(FINFO, "%s is under min-size\n", fname);
1333                 }
1334                 return;
1335         }
1336
1337         if (ignore_existing && statret == 0) {
1338                 if (verbose > 1)
1339                         rprintf(FINFO, "%s exists\n", fname);
1340                 return;
1341         }
1342
1343         if (update_only && statret == 0
1344             && cmp_time(st.st_mtime, file->modtime) > 0) {
1345                 if (verbose > 1)
1346                         rprintf(FINFO, "%s is newer\n", fname);
1347                 return;
1348         }
1349
1350         fnamecmp = fname;
1351         fnamecmp_type = FNAMECMP_FNAME;
1352
1353         if (statret == 0 && !S_ISREG(st.st_mode)) {
1354                 if (delete_item(fname, st.st_mode, "regular file", del_opts) != 0)
1355                         return;
1356                 statret = -1;
1357                 stat_errno = ENOENT;
1358         }
1359
1360         if (statret != 0 && basis_dir[0] != NULL) {
1361                 int j = try_dests_reg(file, fname, ndx, fnamecmpbuf, &st,
1362                                       itemizing, maybe_ATTRS_REPORT, code);
1363                 if (j == -2) {
1364                         if (remove_source_files == 1)
1365                                 goto return_with_success;
1366                         return;
1367                 }
1368                 if (j >= 0) {
1369                         fnamecmp = fnamecmpbuf;
1370                         fnamecmp_type = j;
1371                         statret = 0;
1372                 }
1373         }
1374
1375         real_ret = statret;
1376         real_st = st;
1377
1378         if (partial_dir && (partialptr = partial_dir_fname(fname)) != NULL
1379             && link_stat(partialptr, &partial_st, 0) == 0
1380             && S_ISREG(partial_st.st_mode)) {
1381                 if (statret != 0)
1382                         goto prepare_to_open;
1383         } else
1384                 partialptr = NULL;
1385
1386         if (statret != 0 && fuzzy_dirlist && dry_run <= 1) {
1387                 int j = find_fuzzy(file, fuzzy_dirlist);
1388                 if (j >= 0) {
1389                         fuzzy_file = fuzzy_dirlist->files[j];
1390                         f_name(fuzzy_file, fnamecmpbuf);
1391                         if (verbose > 2) {
1392                                 rprintf(FINFO, "fuzzy basis selected for %s: %s\n",
1393                                         fname, fnamecmpbuf);
1394                         }
1395                         st.st_size = F_LENGTH(fuzzy_file);
1396                         statret = 0;
1397                         fnamecmp = fnamecmpbuf;
1398                         fnamecmp_type = FNAMECMP_FUZZY;
1399                 }
1400         }
1401
1402         if (statret != 0) {
1403                 if (preserve_hard_links && F_IS_HLINKED(file)
1404                     && hard_link_check(file, ndx, fname, statret, &st,
1405                                        itemizing, code, HL_SKIP))
1406                         return;
1407                 if (stat_errno == ENOENT)
1408                         goto notify_others;
1409                 rsyserr(FERROR, stat_errno, "recv_generator: failed to stat %s",
1410                         full_fname(fname));
1411                 return;
1412         }
1413
1414         if (append_mode && st.st_size > F_LENGTH(file))
1415                 return;
1416
1417         if (fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
1418                 ;
1419         else if (fnamecmp_type == FNAMECMP_FUZZY)
1420                 ;
1421         else if (unchanged_file(fnamecmp, file, &st)) {
1422                 if (partialptr) {
1423                         do_unlink(partialptr);
1424                         handle_partial_dir(partialptr, PDIR_DELETE);
1425                 }
1426                 if (itemizing) {
1427                         itemize(file, ndx, real_ret, &real_st,
1428                                 0, 0, NULL);
1429                 }
1430                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1431                 if (preserve_hard_links && F_IS_HLINKED(file))
1432                         hard_link_cluster(file, ndx, itemizing, code, -1);
1433                 if (remove_source_files != 1)
1434                         return;
1435           return_with_success:
1436                 if (!dry_run)
1437                         send_msg_int(MSG_SUCCESS, ndx);
1438                 return;
1439         }
1440
1441   prepare_to_open:
1442         if (partialptr) {
1443                 st = partial_st;
1444                 fnamecmp = partialptr;
1445                 fnamecmp_type = FNAMECMP_PARTIAL_DIR;
1446                 statret = 0;
1447         }
1448
1449         if (!do_xfers || read_batch || whole_file)
1450                 goto notify_others;
1451
1452         if (fuzzy_dirlist) {
1453                 int j = flist_find(fuzzy_dirlist, file);
1454                 if (j >= 0) /* don't use changing file as future fuzzy basis */
1455                         fuzzy_dirlist->files[j]->flags |= FLAG_SENT;
1456         }
1457
1458         /* open the file */
1459         fd = do_open(fnamecmp, O_RDONLY, 0);
1460
1461         if (fd == -1) {
1462                 rsyserr(FERROR, errno, "failed to open %s, continuing",
1463                         full_fname(fnamecmp));
1464           pretend_missing:
1465                 /* pretend the file didn't exist */
1466                 if (preserve_hard_links && F_IS_HLINKED(file)
1467                     && hard_link_check(file, ndx, fname, statret, &st,
1468                                        itemizing, code, HL_SKIP))
1469                         return;
1470                 statret = real_ret = -1;
1471                 goto notify_others;
1472         }
1473
1474         if (inplace && make_backups && fnamecmp_type == FNAMECMP_FNAME) {
1475                 if (!(backupptr = get_backup_name(fname))) {
1476                         close(fd);
1477                         return;
1478                 }
1479                 if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) {
1480                         close(fd);
1481                         goto pretend_missing;
1482                 }
1483                 if (robust_unlink(backupptr) && errno != ENOENT) {
1484                         rsyserr(FERROR, errno, "unlink %s",
1485                                 full_fname(backupptr));
1486                         unmake_file(back_file);
1487                         close(fd);
1488                         return;
1489                 }
1490                 if ((f_copy = do_open(backupptr,
1491                     O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) {
1492                         rsyserr(FERROR, errno, "open %s",
1493                                 full_fname(backupptr));
1494                         unmake_file(back_file);
1495                         close(fd);
1496                         return;
1497                 }
1498                 fnamecmp_type = FNAMECMP_BACKUP;
1499         }
1500
1501         if (verbose > 3) {
1502                 rprintf(FINFO, "gen mapped %s of size %.0f\n",
1503                         fnamecmp, (double)st.st_size);
1504         }
1505
1506         if (verbose > 2)
1507                 rprintf(FINFO, "generating and sending sums for %d\n", ndx);
1508
1509   notify_others:
1510         if (remove_source_files && !delay_updates && !phase)
1511                 increment_active_files(ndx, itemizing, code);
1512         write_int(f_out, ndx);
1513         if (itemizing) {
1514                 int iflags = ITEM_TRANSFER;
1515                 if (always_checksum)
1516                         iflags |= ITEM_REPORT_CHECKSUM;
1517                 if (fnamecmp_type != FNAMECMP_FNAME)
1518                         iflags |= ITEM_BASIS_TYPE_FOLLOWS;
1519                 if (fnamecmp_type == FNAMECMP_FUZZY)
1520                         iflags |= ITEM_XNAME_FOLLOWS;
1521                 itemize(file, -1, real_ret, &real_st, iflags, fnamecmp_type,
1522                         fuzzy_file ? F_BASENAME(fuzzy_file) : NULL);
1523         }
1524
1525         if (!do_xfers) {
1526                 if (preserve_hard_links && F_IS_HLINKED(file))
1527                         hard_link_cluster(file, ndx, itemizing, code, -1);
1528                 return;
1529         }
1530         if (read_batch)
1531                 return;
1532
1533         if (statret != 0 || whole_file) {
1534                 write_sum_head(f_out, NULL);
1535                 return;
1536         }
1537
1538         generate_and_send_sums(fd, st.st_size, f_out, f_copy);
1539
1540         if (f_copy >= 0) {
1541                 close(f_copy);
1542                 set_file_attrs(backupptr, back_file, NULL, 0);
1543                 if (verbose > 1) {
1544                         rprintf(FINFO, "backed up %s to %s\n",
1545                                 fname, backupptr);
1546                 }
1547                 unmake_file(back_file);
1548         }
1549
1550         close(fd);
1551 }
1552
1553 void generate_files(int f_out, struct file_list *flist, char *local_name)
1554 {
1555         int i;
1556         char fbuf[MAXPATHLEN];
1557         int itemizing, maybe_ATTRS_REPORT;
1558         enum logcode code;
1559         int lull_mod = allowed_lull * 5;
1560         int need_retouch_dir_times = preserve_times && !omit_dir_times;
1561         int need_retouch_dir_perms = 0;
1562         int save_ignore_existing = ignore_existing;
1563         int save_ignore_non_existing = ignore_non_existing;
1564         int save_do_progress = do_progress;
1565         int save_make_backups = make_backups;
1566         int dir_tweaking = !(list_only || local_name || dry_run);
1567
1568         if (protocol_version >= 29) {
1569                 itemizing = 1;
1570                 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
1571                 code = logfile_format_has_i ? FNONE : FLOG;
1572         } else if (am_daemon) {
1573                 itemizing = logfile_format_has_i && do_xfers;
1574                 maybe_ATTRS_REPORT = ATTRS_REPORT;
1575                 code = itemizing || !do_xfers ? FCLIENT : FINFO;
1576         } else if (!am_server) {
1577                 itemizing = stdout_format_has_i;
1578                 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
1579                 code = itemizing ? FNONE : FINFO;
1580         } else {
1581                 itemizing = 0;
1582                 maybe_ATTRS_REPORT = ATTRS_REPORT;
1583                 code = FINFO;
1584         }
1585
1586         if (verbose > 2) {
1587                 rprintf(FINFO, "generator starting pid=%ld count=%d\n",
1588                         (long)getpid(), flist->count);
1589         }
1590
1591         if (delete_before && !local_name && flist->count > 0)
1592                 do_delete_pass(flist);
1593         if (delete_during == 2)
1594                 start_delete_temp();
1595         do_progress = 0;
1596
1597         if (append_mode || whole_file < 0)
1598                 whole_file = 0;
1599         if (verbose >= 2) {
1600                 rprintf(FINFO, "delta-transmission %s\n",
1601                         whole_file
1602                         ? "disabled for local transfer or --whole-file"
1603                         : "enabled");
1604         }
1605
1606         /* Since we often fill up the outgoing socket and then just sit around
1607          * waiting for the other 2 processes to do their thing, we don't want
1608          * to exit on a timeout.  If the data stops flowing, the receiver will
1609          * notice that and let us know via the redo pipe (or its closing). */
1610         ignore_timeout = 1;
1611
1612         for (i = 0; i < flist->count; i++) {
1613                 struct file_struct *file = flist->files[i];
1614
1615                 if (!F_IS_ACTIVE(file))
1616                         continue;
1617
1618                 if (local_name)
1619                         strlcpy(fbuf, local_name, sizeof fbuf);
1620                 else
1621                         f_name(file, fbuf);
1622                 recv_generator(fbuf, file, i, itemizing, maybe_ATTRS_REPORT,
1623                                code, f_out);
1624
1625                 /* We need to ensure that any dirs we create have writeable
1626                  * permissions during the time we are putting files within
1627                  * them.  This is then fixed after the transfer is done. */
1628 #ifdef HAVE_CHMOD
1629                 if (!am_root && S_ISDIR(file->mode) && !(file->mode & S_IWUSR)
1630                  && dir_tweaking) {
1631                         mode_t mode = file->mode | S_IWUSR; /* user write */
1632                         char *fname = local_name ? local_name : fbuf;
1633                         if (do_chmod(fname, mode) < 0) {
1634                                 rsyserr(FERROR, errno,
1635                                         "failed to modify permissions on %s",
1636                                         full_fname(fname));
1637                         }
1638                         need_retouch_dir_perms = 1;
1639                 }
1640 #endif
1641
1642                 if (preserve_hard_links)
1643                         check_for_finished_hlinks(itemizing, code);
1644
1645                 if (allowed_lull && !(i % lull_mod))
1646                         maybe_send_keepalive();
1647                 else if (!(i % 200))
1648                         maybe_flush_socket();
1649         }
1650         recv_generator(NULL, NULL, 0, 0, 0, code, -1);
1651         if (delete_during)
1652                 delete_in_dir(NULL, NULL, NULL, NULL);
1653
1654         phase++;
1655         csum_length = SUM_LENGTH;
1656         max_size = min_size = ignore_existing = ignore_non_existing = 0;
1657         update_only = always_checksum = size_only = 0;
1658         ignore_times = 1;
1659         if (append_mode)  /* resend w/o append mode */
1660                 append_mode = -1; /* ... but only longer files */
1661         make_backups = 0; /* avoid a duplicate backup for inplace processing */
1662
1663         if (verbose > 2)
1664                 rprintf(FINFO,"generate_files phase=%d\n",phase);
1665
1666         write_int(f_out, NDX_DONE);
1667
1668         /* files can cycle through the system more than once
1669          * to catch initial checksum errors */
1670         while ((i = get_redo_num(itemizing, code)) != -1) {
1671                 struct file_struct *file = flist->files[i];
1672                 if (local_name)
1673                         strlcpy(fbuf, local_name, sizeof fbuf);
1674                 else
1675                         f_name(file, fbuf);
1676                 recv_generator(fbuf, file, i, itemizing, maybe_ATTRS_REPORT,
1677                                code, f_out);
1678         }
1679
1680         phase++;
1681         ignore_non_existing = save_ignore_non_existing;
1682         ignore_existing = save_ignore_existing;
1683         make_backups = save_make_backups;
1684
1685         if (verbose > 2)
1686                 rprintf(FINFO,"generate_files phase=%d\n",phase);
1687
1688         write_int(f_out, NDX_DONE);
1689         /* Reduce round-trip lag-time for a useless delay-updates phase. */
1690         if (protocol_version >= 29 && !delay_updates)
1691                 write_int(f_out, NDX_DONE);
1692
1693         /* Read MSG_DONE for the redo phase (and any prior messages). */
1694         get_redo_num(itemizing, code);
1695
1696         if (protocol_version >= 29) {
1697                 phase++;
1698                 if (verbose > 2)
1699                         rprintf(FINFO, "generate_files phase=%d\n", phase);
1700                 if (delay_updates)
1701                         write_int(f_out, NDX_DONE);
1702                 /* Read MSG_DONE for delay-updates phase & prior messages. */
1703                 get_redo_num(itemizing, code);
1704         }
1705
1706         do_progress = save_do_progress;
1707         if (delete_delay_fp)
1708                 delayed_deletions(fbuf);
1709         if (delete_after && !local_name && flist->count > 0)
1710                 do_delete_pass(flist);
1711
1712         if ((need_retouch_dir_perms || need_retouch_dir_times) && dir_tweaking) {
1713                 int j = 0;
1714                 /* Now we need to fix any directory permissions that were
1715                  * modified during the transfer and/or re-set any tweaked
1716                  * modified-time values. */
1717                 for (i = 0; i < flist->count; i++) {
1718                         struct file_struct *file = flist->files[i];
1719                         if (!F_IS_ACTIVE(file) || !S_ISDIR(file->mode))
1720                                 continue;
1721                         if (!need_retouch_dir_times && file->mode & S_IWUSR)
1722                                 continue;
1723                         if (file->flags & FLAG_MISSING_DIR) {
1724                                 int missing = file->dir.depth;
1725                                 while (++i < flist->count) {
1726                                         file = flist->files[i];
1727                                         if (file->dir.depth <= missing)
1728                                                 break;
1729                                 }
1730                                 i--;
1731                                 continue;
1732                         }
1733                         recv_generator(f_name(file, NULL), file, i, itemizing,
1734                                        maybe_ATTRS_REPORT, code, -1);
1735                         if (allowed_lull && !(++j % lull_mod))
1736                                 maybe_send_keepalive();
1737                         else if (!(j % 200))
1738                                 maybe_flush_socket();
1739                 }
1740         }
1741         recv_generator(NULL, NULL, 0, 0, 0, code, -1);
1742
1743         if (max_delete >= 0 && deletion_count > max_delete) {
1744                 rprintf(FINFO,
1745                         "Deletions stopped due to --max-delete limit (%d skipped)\n",
1746                         deletion_count - max_delete);
1747                 io_error |= IOERR_DEL_LIMIT;
1748         }
1749
1750         if (verbose > 2)
1751                 rprintf(FINFO,"generate_files finished\n");
1752 }