Change a function name.
[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-2020 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 3 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, visit the http://fsf.org website.
21  */
22
23 #include "rsync.h"
24 #include "inums.h"
25 #include "ifuncs.h"
26
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 inc_recurse;
35 extern int relative_paths;
36 extern int implied_dirs;
37 extern int keep_dirlinks;
38 extern int preserve_acls;
39 extern int preserve_xattrs;
40 extern int preserve_links;
41 extern int preserve_devices;
42 extern int write_devices;
43 extern int preserve_specials;
44 extern int preserve_hard_links;
45 extern int preserve_executability;
46 extern int preserve_perms;
47 extern int preserve_times;
48 extern int delete_mode;
49 extern int delete_before;
50 extern int delete_during;
51 extern int delete_after;
52 extern int missing_args;
53 extern int msgdone_cnt;
54 extern int ignore_errors;
55 extern int remove_source_files;
56 extern int delay_updates;
57 extern int update_only;
58 extern int human_readable;
59 extern int ignore_existing;
60 extern int ignore_non_existing;
61 extern int want_xattr_optim;
62 extern int modify_window;
63 extern int inplace;
64 extern int append_mode;
65 extern int make_backups;
66 extern int csum_length;
67 extern int ignore_times;
68 extern int size_only;
69 extern OFF_T max_size;
70 extern OFF_T min_size;
71 extern int io_error;
72 extern int flist_eof;
73 extern int allowed_lull;
74 extern int sock_f_out;
75 extern int protocol_version;
76 extern int file_total;
77 extern int fuzzy_basis;
78 extern int always_checksum;
79 extern int flist_csum_len;
80 extern char *partial_dir;
81 extern int compare_dest;
82 extern int copy_dest;
83 extern int link_dest;
84 extern int whole_file;
85 extern int list_only;
86 extern int read_batch;
87 extern int write_batch;
88 extern int safe_symlinks;
89 extern long block_size; /* "long" because popt can't set an int32. */
90 extern int unsort_ndx;
91 extern int max_delete;
92 extern int force_delete;
93 extern int one_file_system;
94 extern int skipped_deletes;
95 extern dev_t filesystem_dev;
96 extern mode_t orig_umask;
97 extern uid_t our_uid;
98 extern char *tmpdir;
99 extern char *basis_dir[MAX_BASIS_DIRS+1];
100 extern struct file_list *cur_flist, *first_flist, *dir_flist;
101 extern filter_rule_list filter_list, daemon_filter_list;
102
103 int maybe_ATTRS_REPORT = 0;
104 int maybe_ATTRS_ACCURATE_TIME = 0;
105
106 static dev_t dev_zero;
107 static int deldelay_size = 0, deldelay_cnt = 0;
108 static char *deldelay_buf = NULL;
109 static int deldelay_fd = -1;
110 static int loopchk_limit;
111 static int dir_tweaking;
112 static int symlink_timeset_failed_flags;
113 static int need_retouch_dir_times;
114 static int need_retouch_dir_perms;
115 static const char *solo_file = NULL;
116
117 enum nonregtype {
118         TYPE_DIR, TYPE_SPECIAL, TYPE_DEVICE, TYPE_SYMLINK
119 };
120
121 /* Forward declarations. */
122 #ifdef SUPPORT_HARD_LINKS
123 static void handle_skipped_hlink(struct file_struct *file, int itemizing,
124                                  enum logcode code, int f_out);
125 #endif
126
127 #define EARLY_DELAY_DONE_MSG() (!delay_updates)
128 #define EARLY_DELETE_DONE_MSG() (!(delete_during == 2 || delete_after))
129
130 static int start_delete_delay_temp(void)
131 {
132         char fnametmp[MAXPATHLEN];
133         int save_dry_run = dry_run;
134
135         dry_run = 0;
136         if (!get_tmpname(fnametmp, "deldelay", False)
137          || (deldelay_fd = do_mkstemp(fnametmp, 0600)) < 0) {
138                 rprintf(FINFO, "NOTE: Unable to create delete-delay temp file%s.\n",
139                         inc_recurse ? "" : " -- switching to --delete-after");
140                 delete_during = 0;
141                 delete_after = !inc_recurse;
142                 dry_run = save_dry_run;
143                 return 0;
144         }
145         unlink(fnametmp);
146         dry_run = save_dry_run;
147         return 1;
148 }
149
150 static int flush_delete_delay(void)
151 {
152         if (deldelay_fd < 0 && !start_delete_delay_temp())
153                 return 0;
154         if (write(deldelay_fd, deldelay_buf, deldelay_cnt) != deldelay_cnt) {
155                 rsyserr(FERROR, errno, "flush of delete-delay buffer");
156                 delete_during = 0;
157                 delete_after = !inc_recurse;
158                 close(deldelay_fd);
159                 return 0;
160         }
161         deldelay_cnt = 0;
162         return 1;
163 }
164
165 static int remember_delete(struct file_struct *file, const char *fname, int flags)
166 {
167         int len;
168
169         if (deldelay_cnt == deldelay_size && !flush_delete_delay())
170                 return 0;
171
172         if (flags & DEL_NO_UID_WRITE)
173                 deldelay_buf[deldelay_cnt++] = '!';
174
175         while (1) {
176                 len = snprintf(deldelay_buf + deldelay_cnt,
177                                deldelay_size - deldelay_cnt,
178                                "%x %s%c",
179                                (int)file->mode, fname, '\0');
180                 if ((deldelay_cnt += len) <= deldelay_size)
181                         break;
182                 deldelay_cnt -= len;
183                 if (!flush_delete_delay())
184                         return 0;
185         }
186
187         return 1;
188 }
189
190 static int read_delay_line(char *buf, int *flags_p)
191 {
192         static int read_pos = 0;
193         int j, len, mode;
194         char *bp, *past_space;
195
196         while (1) {
197                 for (j = read_pos; j < deldelay_cnt && deldelay_buf[j]; j++) {}
198                 if (j < deldelay_cnt)
199                         break;
200                 if (deldelay_fd < 0) {
201                         if (j > read_pos)
202                                 goto invalid_data;
203                         return -1;
204                 }
205                 deldelay_cnt -= read_pos;
206                 if (deldelay_cnt == deldelay_size)
207                         goto invalid_data;
208                 if (deldelay_cnt && read_pos) {
209                         memmove(deldelay_buf, deldelay_buf + read_pos,
210                                 deldelay_cnt);
211                 }
212                 len = read(deldelay_fd, deldelay_buf + deldelay_cnt,
213                            deldelay_size - deldelay_cnt);
214                 if (len == 0) {
215                         if (deldelay_cnt) {
216                                 rprintf(FERROR,
217                                     "ERROR: unexpected EOF in delete-delay file.\n");
218                         }
219                         return -1;
220                 }
221                 if (len < 0) {
222                         rsyserr(FERROR, errno,
223                                 "reading delete-delay file");
224                         return -1;
225                 }
226                 deldelay_cnt += len;
227                 read_pos = 0;
228         }
229
230         bp = deldelay_buf + read_pos;
231         if (*bp == '!') {
232                 bp++;
233                 *flags_p = DEL_NO_UID_WRITE;
234         } else
235                 *flags_p = 0;
236
237         if (sscanf(bp, "%x ", &mode) != 1) {
238           invalid_data:
239                 rprintf(FERROR, "ERROR: invalid data in delete-delay file.\n");
240                 return -1;
241         }
242         past_space = strchr(bp, ' ') + 1;
243         len = j - read_pos - (past_space - bp) + 1; /* count the '\0' */
244         read_pos = j + 1;
245
246         if (len > MAXPATHLEN) {
247                 rprintf(FERROR, "ERROR: filename too long in delete-delay file.\n");
248                 return -1;
249         }
250
251         /* The caller needs the name in a MAXPATHLEN buffer, so we copy it
252          * instead of returning a pointer to our buffer. */
253         memcpy(buf, past_space, len);
254
255         return mode;
256 }
257
258 static void do_delayed_deletions(char *delbuf)
259 {
260         int mode, flags;
261
262         if (deldelay_fd >= 0) {
263                 if (deldelay_cnt && !flush_delete_delay())
264                         return;
265                 lseek(deldelay_fd, 0, 0);
266         }
267         while ((mode = read_delay_line(delbuf, &flags)) >= 0)
268                 delete_item(delbuf, mode, flags | DEL_RECURSE);
269         if (deldelay_fd >= 0)
270                 close(deldelay_fd);
271 }
272
273 /* This function is used to implement per-directory deletion, and is used by
274  * all the --delete-WHEN options.  Note that the fbuf pointer must point to a
275  * MAXPATHLEN buffer with the name of the directory in it (the functions we
276  * call will append names onto the end, but the old dir value will be restored
277  * on exit). */
278 static void delete_in_dir(char *fbuf, struct file_struct *file, dev_t *fs_dev)
279 {
280         static int already_warned = 0;
281         static struct hashtable *dev_tbl;
282         struct file_list *dirlist;
283         char delbuf[MAXPATHLEN];
284         int dlen, i;
285
286         if (!fbuf) {
287                 change_local_filter_dir(NULL, 0, 0);
288                 return;
289         }
290
291         if (DEBUG_GTE(DEL, 2))
292                 rprintf(FINFO, "delete_in_dir(%s)\n", fbuf);
293
294         if (allowed_lull)
295                 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
296
297         if (io_error & IOERR_GENERAL && !ignore_errors) {
298                 if (already_warned)
299                         return;
300                 rprintf(FINFO,
301                         "IO error encountered -- skipping file deletion\n");
302                 already_warned = 1;
303                 return;
304         }
305
306         dlen = strlen(fbuf);
307         change_local_filter_dir(fbuf, dlen, F_DEPTH(file));
308
309         if (one_file_system) {
310                 if (!dev_tbl)
311                         dev_tbl = hashtable_create(16, HT_KEY64);
312                 if (file->flags & FLAG_TOP_DIR) {
313                         hashtable_find(dev_tbl, *fs_dev+1, "");
314                         filesystem_dev = *fs_dev;
315                 } else if (filesystem_dev != *fs_dev) {
316                         if (!hashtable_find(dev_tbl, *fs_dev+1, NULL))
317                                 return;
318                         filesystem_dev = *fs_dev; /* it's a prior top-dir dev */
319                 }
320         }
321
322         dirlist = get_dirlist(fbuf, dlen, 0);
323
324         /* If an item in dirlist is not found in flist, delete it
325          * from the filesystem. */
326         for (i = dirlist->used; i--; ) {
327                 struct file_struct *fp = dirlist->files[i];
328                 if (!F_IS_ACTIVE(fp))
329                         continue;
330                 if (fp->flags & FLAG_MOUNT_DIR && S_ISDIR(fp->mode)) {
331                         if (INFO_GTE(MOUNT, 1))
332                                 rprintf(FINFO, "cannot delete mount point: %s\n",
333                                         f_name(fp, NULL));
334                         continue;
335                 }
336                 /* Here we want to match regardless of file type.  Replacement
337                  * of a file with one of another type is handled separately by
338                  * a delete_item call with a DEL_MAKE_ROOM flag. */
339                 if (flist_find_ignore_dirness(cur_flist, fp) < 0) {
340                         int flags = DEL_RECURSE;
341                         if (!(fp->mode & S_IWUSR) && !am_root && fp->flags & FLAG_OWNED_BY_US)
342                                 flags |= DEL_NO_UID_WRITE;
343                         f_name(fp, delbuf);
344                         if (delete_during == 2) {
345                                 if (!remember_delete(fp, delbuf, flags))
346                                         break;
347                         } else
348                                 delete_item(delbuf, fp->mode, flags);
349                 }
350         }
351
352         flist_free(dirlist);
353 }
354
355 /* This deletes any files on the receiving side that are not present on the
356  * sending side.  This is used by --delete-before and --delete-after. */
357 static void do_delete_pass(void)
358 {
359         char fbuf[MAXPATHLEN];
360         STRUCT_STAT st;
361         int j;
362
363         /* dry_run is incremented when the destination doesn't exist yet. */
364         if (dry_run > 1 || list_only)
365                 return;
366
367         for (j = 0; j < cur_flist->used; j++) {
368                 struct file_struct *file = cur_flist->sorted[j];
369
370                 if (!F_IS_ACTIVE(file))
371                         continue;
372
373                 f_name(file, fbuf);
374
375                 if (!(file->flags & FLAG_CONTENT_DIR)) {
376                         change_local_filter_dir(fbuf, strlen(fbuf), F_DEPTH(file));
377                         continue;
378                 }
379
380                 if (DEBUG_GTE(DEL, 1) && file->flags & FLAG_TOP_DIR)
381                         rprintf(FINFO, "deleting in %s\n", fbuf);
382
383                 if (link_stat(fbuf, &st, keep_dirlinks) < 0
384                  || !S_ISDIR(st.st_mode))
385                         continue;
386
387                 delete_in_dir(fbuf, file, &st.st_dev);
388         }
389         delete_in_dir(NULL, NULL, &dev_zero);
390
391         if (INFO_GTE(FLIST, 2) && !am_server)
392                 rprintf(FINFO, "                    \r");
393 }
394
395 static inline int mtime_differs(STRUCT_STAT *stp, struct file_struct *file)
396 {
397 #ifdef ST_MTIME_NSEC
398         return !same_time(stp->st_mtime, stp->ST_MTIME_NSEC, file->modtime, F_MOD_NSEC_or_0(file));
399 #else
400         return !same_time(stp->st_mtime, 0, file->modtime, 0);
401 #endif
402 }
403
404 static inline int perms_differ(struct file_struct *file, stat_x *sxp)
405 {
406         if (preserve_perms)
407                 return !BITS_EQUAL(sxp->st.st_mode, file->mode, CHMOD_BITS);
408
409         if (preserve_executability)
410                 return (sxp->st.st_mode & 0111 ? 1 : 0) ^ (file->mode & 0111 ? 1 : 0);
411
412         return 0;
413 }
414
415 static inline int ownership_differs(struct file_struct *file, stat_x *sxp)
416 {
417         if (am_root && uid_ndx && sxp->st.st_uid != (uid_t)F_OWNER(file))
418                 return 1;
419
420         if (gid_ndx && !(file->flags & FLAG_SKIP_GROUP) && sxp->st.st_gid != (gid_t)F_GROUP(file))
421                 return 1;
422
423         return 0;
424 }
425
426 #ifdef SUPPORT_ACLS
427 static inline int acls_differ(const char *fname, struct file_struct *file, stat_x *sxp)
428 {
429         if (preserve_acls) {
430                 if (!ACL_READY(*sxp))
431                         get_acl(fname, sxp);
432                 if (set_acl(NULL, file, sxp, file->mode))
433                         return 1;
434         }
435
436         return 0;
437 }
438 #endif
439
440 #ifdef SUPPORT_XATTRS
441 static inline int xattrs_differ(const char *fname, struct file_struct *file, stat_x *sxp)
442 {
443         if (preserve_xattrs) {
444                 if (!XATTR_READY(*sxp))
445                         get_xattr(fname, sxp);
446                 if (xattr_diff(file, sxp, 0))
447                         return 1;
448         }
449
450         return 0;
451 }
452 #endif
453
454 int unchanged_attrs(const char *fname, struct file_struct *file, stat_x *sxp)
455 {
456         if (S_ISLNK(file->mode)) {
457 #ifdef CAN_SET_SYMLINK_TIMES
458                 if (preserve_times & PRESERVE_LINK_TIMES && mtime_differs(&sxp->st, file))
459                         return 0;
460 #endif
461 #ifdef CAN_CHMOD_SYMLINK
462                 if (perms_differ(file, sxp))
463                         return 0;
464 #endif
465 #ifdef CAN_CHOWN_SYMLINK
466                 if (ownership_differs(file, sxp))
467                         return 0;
468 #endif
469 #if defined SUPPORT_ACLS && 0 /* no current symlink-ACL support */
470                 if (acls_differ(fname, file, sxp))
471                         return 0;
472 #endif
473 #if defined SUPPORT_XATTRS && !defined NO_SYMLINK_XATTRS
474                 if (xattrs_differ(fname, file, sxp))
475                         return 0;
476 #endif
477         } else {
478                 if (preserve_times && mtime_differs(&sxp->st, file))
479                         return 0;
480                 if (perms_differ(file, sxp))
481                         return 0;
482                 if (ownership_differs(file, sxp))
483                         return 0;
484 #ifdef SUPPORT_ACLS
485                 if (acls_differ(fname, file, sxp))
486                         return 0;
487 #endif
488 #ifdef SUPPORT_XATTRS
489                 if (xattrs_differ(fname, file, sxp))
490                         return 0;
491 #endif
492         }
493
494         return 1;
495 }
496
497 void itemize(const char *fnamecmp, struct file_struct *file, int ndx, int statret,
498              stat_x *sxp, int32 iflags, uchar fnamecmp_type,
499              const char *xname)
500 {
501         if (statret >= 0) { /* A from-dest-dir statret can == 1! */
502                 int keep_time = !preserve_times ? 0
503                     : S_ISDIR(file->mode) ? preserve_times & PRESERVE_DIR_TIMES
504                     : S_ISLNK(file->mode) ? preserve_times & PRESERVE_LINK_TIMES
505                     : 1;
506
507                 if (S_ISREG(file->mode) && F_LENGTH(file) != sxp->st.st_size)
508                         iflags |= ITEM_REPORT_SIZE;
509                 if (file->flags & FLAG_TIME_FAILED) { /* symlinks only */
510                         if (iflags & ITEM_LOCAL_CHANGE)
511                                 iflags |= symlink_timeset_failed_flags;
512                 } else if (keep_time
513                  ? mtime_differs(&sxp->st, file)
514                  : iflags & (ITEM_TRANSFER|ITEM_LOCAL_CHANGE) && !(iflags & ITEM_MATCHED)
515                   && (!(iflags & ITEM_XNAME_FOLLOWS) || *xname))
516                         iflags |= ITEM_REPORT_TIME;
517                 if (atimes_ndx && !S_ISDIR(file->mode) && !S_ISLNK(file->mode)
518                  && !same_time(F_ATIME(file), 0, sxp->st.st_atime, 0))
519                         iflags |= ITEM_REPORT_ATIME;
520 #if !defined HAVE_LCHMOD && !defined HAVE_SETATTRLIST
521                 if (S_ISLNK(file->mode)) {
522                         ;
523                 } else
524 #endif
525                 if (preserve_perms) {
526                         if (!BITS_EQUAL(sxp->st.st_mode, file->mode, CHMOD_BITS))
527                                 iflags |= ITEM_REPORT_PERMS;
528                 } else if (preserve_executability
529                  && ((sxp->st.st_mode & 0111 ? 1 : 0) ^ (file->mode & 0111 ? 1 : 0)))
530                         iflags |= ITEM_REPORT_PERMS;
531                 if (uid_ndx && am_root && (uid_t)F_OWNER(file) != sxp->st.st_uid)
532                         iflags |= ITEM_REPORT_OWNER;
533                 if (gid_ndx && !(file->flags & FLAG_SKIP_GROUP)
534                     && sxp->st.st_gid != (gid_t)F_GROUP(file))
535                         iflags |= ITEM_REPORT_GROUP;
536 #ifdef SUPPORT_ACLS
537                 if (preserve_acls && !S_ISLNK(file->mode)) {
538                         if (!ACL_READY(*sxp))
539                                 get_acl(fnamecmp, sxp);
540                         if (set_acl(NULL, file, sxp, file->mode))
541                                 iflags |= ITEM_REPORT_ACL;
542                 }
543 #endif
544 #ifdef SUPPORT_XATTRS
545                 if (preserve_xattrs) {
546                         if (!XATTR_READY(*sxp))
547                                 get_xattr(fnamecmp, sxp);
548                         if (xattr_diff(file, sxp, 1))
549                                 iflags |= ITEM_REPORT_XATTR;
550                 }
551 #endif
552         } else {
553 #ifdef SUPPORT_XATTRS
554                 if (preserve_xattrs && xattr_diff(file, NULL, 1))
555                         iflags |= ITEM_REPORT_XATTR;
556 #endif
557                 iflags |= ITEM_IS_NEW;
558         }
559
560         iflags &= 0xffff;
561         if ((iflags & (SIGNIFICANT_ITEM_FLAGS|ITEM_REPORT_XATTR) || INFO_GTE(NAME, 2)
562           || stdout_format_has_i > 1 || (xname && *xname)) && !read_batch) {
563                 if (protocol_version >= 29) {
564                         if (ndx >= 0)
565                                 write_ndx(sock_f_out, ndx);
566                         write_shortint(sock_f_out, iflags);
567                         if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
568                                 write_byte(sock_f_out, fnamecmp_type);
569                         if (iflags & ITEM_XNAME_FOLLOWS)
570                                 write_vstring(sock_f_out, xname, strlen(xname));
571 #ifdef SUPPORT_XATTRS
572                         if (preserve_xattrs && do_xfers
573                          && iflags & (ITEM_REPORT_XATTR|ITEM_TRANSFER)) {
574                                 int fd = iflags & ITEM_REPORT_XATTR
575                                       && !(want_xattr_optim && BITS_SET(iflags, ITEM_XNAME_FOLLOWS|ITEM_LOCAL_CHANGE))
576                                        ? sock_f_out : -1;
577                                 send_xattr_request(NULL, file, fd);
578                         }
579 #endif
580                 } else if (ndx >= 0) {
581                         enum logcode code = logfile_format_has_i ? FINFO : FCLIENT;
582                         log_item(code, file, iflags, xname);
583                 }
584         }
585 }
586
587
588 /* Perform our quick-check heuristic for determining if a file is unchanged. */
589 int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
590 {
591         if (st->st_size != F_LENGTH(file))
592                 return 0;
593
594         /* if always checksum is set then we use the checksum instead
595            of the file time to determine whether to sync */
596         if (always_checksum > 0 && S_ISREG(st->st_mode)) {
597                 char sum[MAX_DIGEST_LEN];
598                 file_checksum(fn, st, sum);
599                 return memcmp(sum, F_SUM(file), flist_csum_len) == 0;
600         }
601
602         if (size_only > 0)
603                 return 1;
604
605         if (ignore_times)
606                 return 0;
607
608         return !mtime_differs(st, file);
609 }
610
611
612 /*
613  * set (initialize) the size entries in the per-file sum_struct
614  * calculating dynamic block and checksum sizes.
615  *
616  * This is only called from generate_and_send_sums() but is a separate
617  * function to encapsulate the logic.
618  *
619  * The block size is a rounded square root of file length.
620  *
621  * The checksum size is determined according to:
622  *     blocksum_bits = BLOCKSUM_BIAS + 2*log2(file_len) - log2(block_len)
623  * provided by Donovan Baarda which gives a probability of rsync
624  * algorithm corrupting data and falling back using the whole md4
625  * checksums.
626  *
627  * This might be made one of several selectable heuristics.
628  */
629 static void sum_sizes_sqroot(struct sum_struct *sum, int64 len)
630 {
631         int32 blength;
632         int s2length;
633         int64 l;
634
635         if (len < 0) {
636                 /* The file length overflowed our int64 var, so we can't process this file. */
637                 sum->count = -1; /* indicate overflow error */
638                 return;
639         }
640
641         if (block_size)
642                 blength = block_size;
643         else if (len <= BLOCK_SIZE * BLOCK_SIZE)
644                 blength = BLOCK_SIZE;
645         else {
646                 int32 max_blength = protocol_version < 30 ? OLD_MAX_BLOCK_SIZE : MAX_BLOCK_SIZE;
647                 int32 c;
648                 int cnt;
649                 for (c = 1, l = len, cnt = 0; l >>= 2; c <<= 1, cnt++) {}
650                 if (c < 0 || c >= max_blength)
651                         blength = max_blength;
652                 else {
653                     blength = 0;
654                     do {
655                             blength |= c;
656                             if (len < (int64)blength * blength)
657                                     blength &= ~c;
658                             c >>= 1;
659                     } while (c >= 8);   /* round to multiple of 8 */
660                     blength = MAX(blength, BLOCK_SIZE);
661                 }
662         }
663
664         if (protocol_version < 27) {
665                 s2length = csum_length;
666         } else if (csum_length == SUM_LENGTH) {
667                 s2length = SUM_LENGTH;
668         } else {
669                 int32 c;
670                 int b = BLOCKSUM_BIAS;
671                 for (l = len; l >>= 1; b += 2) {}
672                 for (c = blength; (c >>= 1) && b; b--) {}
673                 /* add a bit, subtract rollsum, round up. */
674                 s2length = (b + 1 - 32 + 7) / 8; /* --optimize in compiler-- */
675                 s2length = MAX(s2length, csum_length);
676                 s2length = MIN(s2length, SUM_LENGTH);
677         }
678
679         sum->flength    = len;
680         sum->blength    = blength;
681         sum->s2length   = s2length;
682         sum->remainder  = (int32)(len % blength);
683         sum->count      = (int32)(l = (len / blength) + (sum->remainder != 0));
684
685         if ((int64)sum->count != l)
686                 sum->count = -1;
687
688         if (sum->count && DEBUG_GTE(DELTASUM, 2)) {
689                 rprintf(FINFO,
690                         "count=%s rem=%ld blength=%ld s2length=%d flength=%s\n",
691                         big_num(sum->count), (long)sum->remainder, (long)sum->blength,
692                         sum->s2length, big_num(sum->flength));
693         }
694 }
695
696
697 /*
698  * Generate and send a stream of signatures/checksums that describe a buffer
699  *
700  * Generate approximately one checksum every block_len bytes.
701  */
702 static int generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy)
703 {
704         int32 i;
705         struct map_struct *mapbuf;
706         struct sum_struct sum;
707         OFF_T offset = 0;
708
709         sum_sizes_sqroot(&sum, len);
710         if (sum.count < 0)
711                 return -1;
712         write_sum_head(f_out, &sum);
713
714         if (append_mode > 0 && f_copy < 0)
715                 return 0;
716
717         if (len > 0)
718                 mapbuf = map_file(fd, len, MAX_MAP_SIZE, sum.blength);
719         else
720                 mapbuf = NULL;
721
722         for (i = 0; i < sum.count; i++) {
723                 int32 n1 = (int32)MIN(len, (OFF_T)sum.blength);
724                 char *map = map_ptr(mapbuf, offset, n1);
725                 char sum2[SUM_LENGTH];
726                 uint32 sum1;
727
728                 len -= n1;
729                 offset += n1;
730
731                 if (f_copy >= 0) {
732                         full_write(f_copy, map, n1);
733                         if (append_mode > 0)
734                                 continue;
735                 }
736
737                 sum1 = get_checksum1(map, n1);
738                 get_checksum2(map, n1, sum2);
739
740                 if (DEBUG_GTE(DELTASUM, 3)) {
741                         rprintf(FINFO,
742                                 "chunk[%s] offset=%s len=%ld sum1=%08lx\n",
743                                 big_num(i), big_num(offset - n1), (long)n1,
744                                 (unsigned long)sum1);
745                 }
746                 write_int(f_out, sum1);
747                 write_buf(f_out, sum2, sum.s2length);
748         }
749
750         if (mapbuf)
751                 unmap_file(mapbuf);
752
753         return 0;
754 }
755
756
757 /* Try to find a filename in the same dir as "fname" with a similar name. */
758 static struct file_struct *find_fuzzy(struct file_struct *file, struct file_list *dirlist_array[], uchar *fnamecmp_type_ptr)
759 {
760         int fname_len, fname_suf_len;
761         const char *fname_suf, *fname = file->basename;
762         uint32 lowest_dist = 25 << 16; /* ignore a distance greater than 25 */
763         int i, j;
764         struct file_struct *lowest_fp = NULL;
765
766         fname_len = strlen(fname);
767         fname_suf = find_filename_suffix(fname, fname_len, &fname_suf_len);
768
769         /* Try to find an exact size+mtime match first. */
770         for (i = 0; i < fuzzy_basis; i++) {
771                 struct file_list *dirlist = dirlist_array[i];
772
773                 if (!dirlist)
774                         continue;
775
776                 for (j = 0; j < dirlist->used; j++) {
777                         struct file_struct *fp = dirlist->files[j];
778
779                         if (!F_IS_ACTIVE(fp))
780                                 continue;
781
782                         if (!S_ISREG(fp->mode) || !F_LENGTH(fp) || fp->flags & FLAG_FILE_SENT)
783                                 continue;
784
785                         if (F_LENGTH(fp) == F_LENGTH(file) && same_time(fp->modtime, 0, file->modtime, 0)) {
786                                 if (DEBUG_GTE(FUZZY, 2))
787                                         rprintf(FINFO, "fuzzy size/modtime match for %s\n", f_name(fp, NULL));
788                                 *fnamecmp_type_ptr = FNAMECMP_FUZZY + i;
789                                 return fp;
790                         }
791
792                 }
793         }
794
795         for (i = 0; i < fuzzy_basis; i++) {
796                 struct file_list *dirlist = dirlist_array[i];
797
798                 if (!dirlist)
799                         continue;
800
801                 for (j = 0; j < dirlist->used; j++) {
802                         struct file_struct *fp = dirlist->files[j];
803                         const char *suf, *name;
804                         int len, suf_len;
805                         uint32 dist;
806
807                         if (!F_IS_ACTIVE(fp))
808                                 continue;
809
810                         if (!S_ISREG(fp->mode) || !F_LENGTH(fp) || fp->flags & FLAG_FILE_SENT)
811                                 continue;
812
813                         name = fp->basename;
814                         len = strlen(name);
815                         suf = find_filename_suffix(name, len, &suf_len);
816
817                         dist = fuzzy_distance(name, len, fname, fname_len);
818                         /* Add some extra weight to how well the suffixes match. */
819                         dist += fuzzy_distance(suf, suf_len, fname_suf, fname_suf_len) * 10;
820                         if (DEBUG_GTE(FUZZY, 2)) {
821                                 rprintf(FINFO, "fuzzy distance for %s = %d.%05d\n",
822                                         f_name(fp, NULL), (int)(dist>>16), (int)(dist&0xFFFF));
823                         }
824                         if (dist <= lowest_dist) {
825                                 lowest_dist = dist;
826                                 lowest_fp = fp;
827                                 *fnamecmp_type_ptr = FNAMECMP_FUZZY + i;
828                         }
829                 }
830         }
831
832         return lowest_fp;
833 }
834
835 /* Copy a file found in our --copy-dest handling. */
836 static int copy_altdest_file(const char *src, const char *dest, struct file_struct *file)
837 {
838         char buf[MAXPATHLEN];
839         const char *copy_to, *partialptr;
840         int save_preserve_xattrs = preserve_xattrs;
841         int ok, fd_w;
842
843         if (inplace) {
844                 /* Let copy_file open the destination in place. */
845                 fd_w = -1;
846                 copy_to = dest;
847         } else {
848                 fd_w = open_tmpfile(buf, dest, file);
849                 if (fd_w < 0)
850                         return -1;
851                 copy_to = buf;
852         }
853         cleanup_set(copy_to, NULL, NULL, -1, -1);
854         if (copy_file(src, copy_to, fd_w, file->mode) < 0) {
855                 if (INFO_GTE(COPY, 1)) {
856                         rsyserr(FINFO, errno, "copy_file %s => %s",
857                                 full_fname(src), copy_to);
858                 }
859                 /* Try to clean up. */
860                 unlink(copy_to);
861                 cleanup_disable();
862                 return -1;
863         }
864         partialptr = partial_dir ? partial_dir_fname(dest) : NULL;
865         preserve_xattrs = 0; /* xattrs were copied with file */
866         ok = finish_transfer(dest, copy_to, src, partialptr, file, 1, 0);
867         preserve_xattrs = save_preserve_xattrs;
868         cleanup_disable();
869         return ok ? 0 : -1;
870 }
871
872 /* This is only called for regular files.  We return -2 if we've finished
873  * handling the file, -1 if no dest-linking occurred, or a non-negative
874  * value if we found an alternate basis file.  If we're called with the
875  * find_exact_for_existing flag, the destination file already exists, so
876  * we only try to find an exact alt-dest match.  In this case, the returns
877  * are only -2 & -1 (both as above). */
878 static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
879                          char *cmpbuf, stat_x *sxp, int find_exact_for_existing,
880                          int itemizing, enum logcode code)
881 {
882         STRUCT_STAT real_st = sxp->st;
883         int best_match = -1;
884         int match_level = 0;
885         int j = 0;
886
887         do {
888                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
889                 if (link_stat(cmpbuf, &sxp->st, 0) < 0 || !S_ISREG(sxp->st.st_mode))
890                         continue;
891                 if (match_level == 0) {
892                         best_match = j;
893                         match_level = 1;
894                 }
895                 if (!unchanged_file(cmpbuf, file, &sxp->st))
896                         continue;
897                 if (match_level == 1) {
898                         best_match = j;
899                         match_level = 2;
900                 }
901                 if (unchanged_attrs(cmpbuf, file, sxp)) {
902                         best_match = j;
903                         match_level = 3;
904                         break;
905                 }
906                 free_stat_x(sxp);
907         } while (basis_dir[++j] != NULL);
908
909         if (!match_level)
910                 goto got_nothing_for_ya;
911
912         if (j != best_match) {
913                 j = best_match;
914                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
915                 if (link_stat(cmpbuf, &sxp->st, 0) < 0)
916                         goto got_nothing_for_ya;
917         }
918
919         if (match_level == 3 && !copy_dest) {
920                 if (find_exact_for_existing) {
921                         if (link_dest && real_st.st_dev == sxp->st.st_dev && real_st.st_ino == sxp->st.st_ino)
922                                 return -1;
923                         if (do_unlink(fname) < 0 && errno != ENOENT)
924                                 goto got_nothing_for_ya;
925                 }
926 #ifdef SUPPORT_HARD_LINKS
927                 if (link_dest) {
928                         if (!hard_link_one(file, fname, cmpbuf, 1))
929                                 goto try_a_copy;
930                         if (atimes_ndx)
931                                 set_file_attrs(fname, file, sxp, NULL, 0);
932                         if (preserve_hard_links && F_IS_HLINKED(file))
933                                 finish_hard_link(file, fname, ndx, &sxp->st, itemizing, code, j);
934                         if (!maybe_ATTRS_REPORT && (INFO_GTE(NAME, 2) || stdout_format_has_i > 1)) {
935                                 itemize(cmpbuf, file, ndx, 1, sxp,
936                                         ITEM_LOCAL_CHANGE | ITEM_XNAME_FOLLOWS,
937                                         0, "");
938                         }
939                 } else
940 #endif
941                 {
942                         if (itemizing)
943                                 itemize(cmpbuf, file, ndx, 0, sxp, 0, 0, NULL);
944                 }
945                 if (INFO_GTE(NAME, 2) && maybe_ATTRS_REPORT)
946                         rprintf(FCLIENT, "%s is uptodate\n", fname);
947                 return -2;
948         }
949
950         if (find_exact_for_existing)
951                 goto got_nothing_for_ya;
952
953         if (match_level >= 2) {
954 #ifdef SUPPORT_HARD_LINKS
955           try_a_copy: /* Copy the file locally. */
956 #endif
957                 if (!dry_run && copy_altdest_file(cmpbuf, fname, file) < 0) {
958                         if (find_exact_for_existing) /* Can get here via hard-link failure */
959                                 goto got_nothing_for_ya;
960                         return -1;
961                 }
962                 if (itemizing)
963                         itemize(cmpbuf, file, ndx, 0, sxp, ITEM_LOCAL_CHANGE, 0, NULL);
964                 if (maybe_ATTRS_REPORT
965                  && ((!itemizing && INFO_GTE(NAME, 1) && match_level == 2)
966                   || (INFO_GTE(NAME, 2) && match_level == 3))) {
967                         code = match_level == 3 ? FCLIENT : FINFO;
968                         rprintf(code, "%s%s\n", fname,
969                                 match_level == 3 ? " is uptodate" : "");
970                 }
971 #ifdef SUPPORT_HARD_LINKS
972                 if (preserve_hard_links && F_IS_HLINKED(file))
973                         finish_hard_link(file, fname, ndx, &sxp->st, itemizing, code, -1);
974 #endif
975                 return -2;
976         }
977
978         return FNAMECMP_BASIS_DIR_LOW + j;
979
980 got_nothing_for_ya:
981         sxp->st = real_st;
982         return -1;
983 }
984
985 /* This is only called for non-regular files.  We return -2 if we've finished
986  * handling the file, or -1 if no dest-linking occurred, or a non-negative
987  * value if we found an alternate basis file. */
988 static int try_dests_non(struct file_struct *file, char *fname, int ndx,
989                          char *cmpbuf, stat_x *sxp, int itemizing,
990                          enum logcode code)
991 {
992         int best_match = -1;
993         int match_level = 0;
994         enum nonregtype type;
995         uint32 *devp;
996 #ifdef SUPPORT_LINKS
997         char lnk[MAXPATHLEN];
998         int len;
999 #endif
1000         int j = 0;
1001
1002 #ifndef SUPPORT_LINKS
1003         if (S_ISLNK(file->mode))
1004                 return -1;
1005 #endif
1006         if (S_ISDIR(file->mode)) {
1007                 type = TYPE_DIR;
1008         } else if (IS_SPECIAL(file->mode))
1009                 type = TYPE_SPECIAL;
1010         else if (IS_DEVICE(file->mode))
1011                 type = TYPE_DEVICE;
1012 #ifdef SUPPORT_LINKS
1013         else if (S_ISLNK(file->mode))
1014                 type = TYPE_SYMLINK;
1015 #endif
1016         else {
1017                 rprintf(FERROR,
1018                         "internal: try_dests_non() called with invalid mode (%o)\n",
1019                         (int)file->mode);
1020                 exit_cleanup(RERR_UNSUPPORTED);
1021         }
1022
1023         do {
1024                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
1025                 if (link_stat(cmpbuf, &sxp->st, 0) < 0)
1026                         continue;
1027                 switch (type) {
1028                 case TYPE_DIR:
1029                         if (!S_ISDIR(sxp->st.st_mode))
1030                                 continue;
1031                         break;
1032                 case TYPE_SPECIAL:
1033                         if (!IS_SPECIAL(sxp->st.st_mode))
1034                                 continue;
1035                         break;
1036                 case TYPE_DEVICE:
1037                         if (!IS_DEVICE(sxp->st.st_mode))
1038                                 continue;
1039                         break;
1040                 case TYPE_SYMLINK:
1041 #ifdef SUPPORT_LINKS
1042                         if (!S_ISLNK(sxp->st.st_mode))
1043                                 continue;
1044                         break;
1045 #else
1046                         return -1;
1047 #endif
1048                 }
1049                 if (match_level < 1) {
1050                         match_level = 1;
1051                         best_match = j;
1052                 }
1053                 switch (type) {
1054                 case TYPE_DIR:
1055                 case TYPE_SPECIAL:
1056                         break;
1057                 case TYPE_DEVICE:
1058                         devp = F_RDEV_P(file);
1059                         if (sxp->st.st_rdev != MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp)))
1060                                 continue;
1061                         break;
1062                 case TYPE_SYMLINK:
1063 #ifdef SUPPORT_LINKS
1064                         if ((len = do_readlink(cmpbuf, lnk, MAXPATHLEN-1)) <= 0)
1065                                 continue;
1066                         lnk[len] = '\0';
1067                         if (strcmp(lnk, F_SYMLINK(file)) != 0)
1068                                 continue;
1069                         break;
1070 #else
1071                         return -1;
1072 #endif
1073                 }
1074                 if (match_level < 2) {
1075                         match_level = 2;
1076                         best_match = j;
1077                 }
1078                 if (unchanged_attrs(cmpbuf, file, sxp)) {
1079                         match_level = 3;
1080                         best_match = j;
1081                         break;
1082                 }
1083         } while (basis_dir[++j] != NULL);
1084
1085         if (!match_level)
1086                 return -1;
1087
1088         if (j != best_match) {
1089                 j = best_match;
1090                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
1091                 if (link_stat(cmpbuf, &sxp->st, 0) < 0)
1092                         return -1;
1093         }
1094
1095         if (match_level == 3) {
1096 #ifdef SUPPORT_HARD_LINKS
1097                 if (link_dest
1098 #ifndef CAN_HARDLINK_SYMLINK
1099                  && !S_ISLNK(file->mode)
1100 #endif
1101 #ifndef CAN_HARDLINK_SPECIAL
1102                  && !IS_SPECIAL(file->mode) && !IS_DEVICE(file->mode)
1103 #endif
1104                  && !S_ISDIR(file->mode)) {
1105                         if (do_link(cmpbuf, fname) < 0) {
1106                                 rsyserr(FERROR_XFER, errno,
1107                                         "failed to hard-link %s with %s",
1108                                         cmpbuf, fname);
1109                                 return j;
1110                         }
1111                         if (preserve_hard_links && F_IS_HLINKED(file))
1112                                 finish_hard_link(file, fname, ndx, NULL, itemizing, code, -1);
1113                 } else
1114 #endif
1115                         match_level = 2;
1116                 if (itemizing && stdout_format_has_i
1117                  && (INFO_GTE(NAME, 2) || stdout_format_has_i > 1)) {
1118                         int chg = compare_dest && type != TYPE_DIR ? 0
1119                             : ITEM_LOCAL_CHANGE + (match_level == 3 ? ITEM_XNAME_FOLLOWS : 0);
1120                         char *lp = match_level == 3 ? "" : NULL;
1121                         itemize(cmpbuf, file, ndx, 0, sxp, chg + ITEM_MATCHED, 0, lp);
1122                 }
1123                 if (INFO_GTE(NAME, 2) && maybe_ATTRS_REPORT) {
1124                         rprintf(FCLIENT, "%s%s is uptodate\n",
1125                                 fname, type == TYPE_DIR ? "/" : "");
1126                 }
1127                 return -2;
1128         }
1129
1130         return j;
1131 }
1132
1133 static void list_file_entry(struct file_struct *f)
1134 {
1135         char permbuf[PERMSTRING_SIZE];
1136         const char *mtime_str = timestring(f->modtime);
1137         int size_width = human_readable ? 14 : 11;
1138         int mtime_width = 1 + strlen(mtime_str);
1139         int atime_width = atimes_ndx ? mtime_width : 0;
1140
1141         if (!F_IS_ACTIVE(f)) {
1142                 /* this can happen if duplicate names were removed */
1143                 return;
1144         }
1145
1146         /* TODO: indicate '+' if the entry has an ACL. */
1147
1148         if (missing_args == 2 && f->mode == 0) {
1149                 rprintf(FINFO, "%-*s %s\n",
1150                         10 + 1 + size_width + mtime_width + atime_width, "*missing",
1151                         f_name(f, NULL));
1152         } else {
1153                 const char *atime_str = atimes_ndx && !S_ISDIR(f->mode) ? timestring(F_ATIME(f)) : "";
1154                 const char *arrow, *lnk;
1155
1156                 permstring(permbuf, f->mode);
1157
1158 #ifdef SUPPORT_LINKS
1159                 if (preserve_links && S_ISLNK(f->mode)) {
1160                         arrow = " -> ";
1161                         lnk = F_SYMLINK(f);
1162                 } else
1163 #endif
1164                         arrow = lnk = "";
1165
1166                 rprintf(FINFO, "%s %*s %s%*s %s%s%s\n",
1167                         permbuf, size_width, human_num(F_LENGTH(f)),
1168                         timestring(f->modtime), atime_width, atime_str,
1169                         f_name(f, NULL), arrow, lnk);
1170         }
1171 }
1172
1173 static int phase = 0;
1174 static int dflt_perms;
1175
1176 static int implied_dirs_are_missing;
1177 /* Helper for recv_generator's skip_dir and dry_missing_dir tests. */
1178 static BOOL is_below(struct file_struct *file, struct file_struct *subtree)
1179 {
1180         return F_DEPTH(file) > F_DEPTH(subtree)
1181                 && (!implied_dirs_are_missing || f_name_has_prefix(file, subtree));
1182 }
1183
1184 /* Acts on the indicated item in cur_flist whose name is fname.  If a dir,
1185  * make sure it exists, and has the right permissions/timestamp info.  For
1186  * all other non-regular files (symlinks, etc.) we create them here.  For
1187  * regular files that have changed, we try to find a basis file and then
1188  * start sending checksums.  The ndx is the file's unique index value.
1189  *
1190  * The fname parameter must point to a MAXPATHLEN buffer!  (e.g it gets
1191  * passed to delete_item(), which can use it during a recursive delete.)
1192  *
1193  * Note that f_out is set to -1 when doing final directory-permission and
1194  * modification-time repair. */
1195 static void recv_generator(char *fname, struct file_struct *file, int ndx,
1196                            int itemizing, enum logcode code, int f_out)
1197 {
1198         static const char *parent_dirname = "";
1199         static struct file_struct *prior_dir_file = NULL;
1200         /* Missing dir not created due to --dry-run; will still be scanned. */
1201         static struct file_struct *dry_missing_dir = NULL;
1202         /* Missing dir whose contents are skipped altogether due to
1203          * --ignore-non-existing, daemon exclude, or mkdir failure. */
1204         static struct file_struct *skip_dir = NULL;
1205         static struct file_list *fuzzy_dirlist[MAX_BASIS_DIRS+1];
1206         static int need_fuzzy_dirlist = 0;
1207         struct file_struct *fuzzy_file = NULL;
1208         int fd = -1, f_copy = -1;
1209         stat_x sx, real_sx;
1210         STRUCT_STAT partial_st;
1211         struct file_struct *back_file = NULL;
1212         int statret, real_ret, stat_errno;
1213         char *fnamecmp, *partialptr, *backupptr = NULL;
1214         char fnamecmpbuf[MAXPATHLEN];
1215         uchar fnamecmp_type;
1216         int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0;
1217         int is_dir = !S_ISDIR(file->mode) ? 0
1218                    : inc_recurse && ndx != cur_flist->ndx_start - 1 ? -1
1219                    : 1;
1220
1221         if (DEBUG_GTE(GENR, 1))
1222                 rprintf(FINFO, "recv_generator(%s,%d)\n", fname, ndx);
1223
1224         if (list_only) {
1225                 if (is_dir < 0
1226                  || (is_dir && !implied_dirs && file->flags & FLAG_IMPLIED_DIR))
1227                         return;
1228                 list_file_entry(file);
1229                 return;
1230         }
1231
1232         maybe_ATTRS_ACCURATE_TIME = always_checksum ? ATTRS_ACCURATE_TIME : 0;
1233
1234         if (skip_dir) {
1235                 if (is_below(file, skip_dir)) {
1236                         if (is_dir)
1237                                 file->flags |= FLAG_MISSING_DIR;
1238 #ifdef SUPPORT_HARD_LINKS
1239                         else if (F_IS_HLINKED(file))
1240                                 handle_skipped_hlink(file, itemizing, code, f_out);
1241 #endif
1242                         return;
1243                 }
1244                 skip_dir = NULL;
1245         }
1246
1247         init_stat_x(&sx);
1248         if (daemon_filter_list.head && (*fname != '.' || fname[1])) {
1249                 if (check_filter(&daemon_filter_list, FLOG, fname, is_dir) < 0) {
1250                         if (is_dir < 0)
1251                                 return;
1252 #ifdef SUPPORT_HARD_LINKS
1253                         if (F_IS_HLINKED(file))
1254                                 handle_skipped_hlink(file, itemizing, code, f_out);
1255 #endif
1256                         rprintf(FERROR_XFER,
1257                                 "ERROR: daemon refused to receive %s \"%s\"\n",
1258                                 is_dir ? "directory" : "file", fname);
1259                         if (is_dir)
1260                                 goto skipping_dir_contents;
1261                         return;
1262                 }
1263         }
1264
1265         if (dry_run > 1 || (dry_missing_dir && is_below(file, dry_missing_dir))) {
1266                 int i;
1267           parent_is_dry_missing:
1268                 for (i = 0; i < fuzzy_basis; i++) {
1269                         if (fuzzy_dirlist[i]) {
1270                                 flist_free(fuzzy_dirlist[i]);
1271                                 fuzzy_dirlist[i] = NULL;
1272                         }
1273                 }
1274                 parent_dirname = "";
1275                 statret = -1;
1276                 stat_errno = ENOENT;
1277         } else {
1278                 const char *dn = file->dirname ? file->dirname : ".";
1279                 dry_missing_dir = NULL;
1280                 if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) {
1281                         /* Each parent dir must be in the file list or the flist data is bad.
1282                          * Optimization: most of the time the parent dir will be the last dir
1283                          * this function was asked to process in the file list. */
1284                         if (!inc_recurse
1285                          && (*dn != '.' || dn[1]) /* Avoid an issue with --relative and the "." dir. */
1286                          && (!prior_dir_file || strcmp(dn, f_name(prior_dir_file, NULL)) != 0)
1287                          && flist_find_name(cur_flist, dn, 1) < 0) {
1288                                 /* The --delete-missing-args option can actually put invalid entries into
1289                                  * the file list, so if that option was specified, we'll just complain about
1290                                  * it and allow it. */
1291                                 if (missing_args == 2 && file->mode == 0)
1292                                         rprintf(FERROR, "WARNING: parent dir is absent in the file list: %s\n", dn);
1293                                 else {
1294                                         rprintf(FERROR, "ABORTING due to invalid path from sender: %s/%s\n",
1295                                                 dn, file->basename);
1296                                         exit_cleanup(RERR_PROTOCOL);
1297                                 }
1298                         }
1299                         if (relative_paths && !implied_dirs
1300                          && do_stat(dn, &sx.st) < 0) {
1301                                 if (dry_run)
1302                                         goto parent_is_dry_missing;
1303                                 if (make_path(fname, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0) {
1304                                         rsyserr(FERROR_XFER, errno,
1305                                                 "recv_generator: mkdir %s failed",
1306                                                 full_fname(dn));
1307                                 }
1308                         }
1309                         if (fuzzy_basis) {
1310                                 int i;
1311                                 for (i = 0; i < fuzzy_basis; i++) {
1312                                         if (fuzzy_dirlist[i]) {
1313                                                 flist_free(fuzzy_dirlist[i]);
1314                                                 fuzzy_dirlist[i] = NULL;
1315                                         }
1316                                 }
1317                                 need_fuzzy_dirlist = 1;
1318                         }
1319 #ifdef SUPPORT_ACLS
1320                         if (!preserve_perms)
1321                                 dflt_perms = default_perms_for_dir(dn);
1322 #endif
1323                 }
1324                 parent_dirname = dn;
1325
1326                 statret = link_stat(fname, &sx.st, keep_dirlinks && is_dir);
1327                 stat_errno = errno;
1328         }
1329
1330         if (missing_args == 2 && file->mode == 0) {
1331                 if (filter_list.head && check_filter(&filter_list, FINFO, fname, is_dir) < 0)
1332                         return;
1333                 if (statret == 0)
1334                         delete_item(fname, sx.st.st_mode, del_opts);
1335                 return;
1336         }
1337
1338         if (ignore_non_existing > 0 && statret == -1 && stat_errno == ENOENT) {
1339                 if (is_dir) {
1340                         if (is_dir < 0)
1341                                 return;
1342                         skip_dir = file;
1343                         file->flags |= FLAG_MISSING_DIR;
1344                 }
1345 #ifdef SUPPORT_HARD_LINKS
1346                 else if (F_IS_HLINKED(file))
1347                         handle_skipped_hlink(file, itemizing, code, f_out);
1348 #endif
1349                 if (INFO_GTE(SKIP, 1)) {
1350                         rprintf(FINFO, "not creating new %s \"%s\"\n",
1351                                 is_dir ? "directory" : "file", fname);
1352                 }
1353                 return;
1354         }
1355
1356         if (statret == 0 && !(sx.st.st_mode & S_IWUSR)
1357          && !am_root && sx.st.st_uid == our_uid)
1358                 del_opts |= DEL_NO_UID_WRITE;
1359
1360         if (ignore_existing > 0 && statret == 0
1361          && (!is_dir || !S_ISDIR(sx.st.st_mode))) {
1362                 if (INFO_GTE(SKIP, 1) && is_dir >= 0)
1363                         rprintf(FINFO, "%s exists\n", fname);
1364 #ifdef SUPPORT_HARD_LINKS
1365                 if (F_IS_HLINKED(file))
1366                         handle_skipped_hlink(file, itemizing, code, f_out);
1367 #endif
1368                 goto cleanup;
1369         }
1370
1371         fnamecmp = fname;
1372
1373         if (is_dir) {
1374                 mode_t added_perms;
1375                 if (!implied_dirs && file->flags & FLAG_IMPLIED_DIR)
1376                         goto cleanup;
1377                 if (am_root < 0) {
1378                         /* For --fake-super, the dir must be useable by the copying
1379                          * user, just like it would be for root. */
1380                         added_perms = S_IRUSR|S_IWUSR|S_IXUSR;
1381                 } else
1382                         added_perms = 0;
1383                 if (is_dir < 0) {
1384                         if (!(preserve_times & PRESERVE_DIR_TIMES))
1385                                 goto cleanup;
1386                         /* In inc_recurse mode we want to make sure any missing
1387                          * directories get created while we're still processing
1388                          * the parent dir (which allows us to touch the parent
1389                          * dir's mtime right away).  We will handle the dir in
1390                          * full later (right before we handle its contents). */
1391                         if (statret == 0
1392                          && (S_ISDIR(sx.st.st_mode)
1393                           || delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_DIR) != 0))
1394                                 goto cleanup; /* Any errors get reported later. */
1395                         if (do_mkdir(fname, (file->mode|added_perms) & 0700) == 0)
1396                                 file->flags |= FLAG_DIR_CREATED;
1397                         goto cleanup;
1398                 }
1399                 /* The file to be received is a directory, so we need
1400                  * to prepare appropriately.  If there is already a
1401                  * file of that name and it is *not* a directory, then
1402                  * we need to delete it.  If it doesn't exist, then
1403                  * (perhaps recursively) create it. */
1404                 if (statret == 0 && !S_ISDIR(sx.st.st_mode)) {
1405                         if (delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_DIR) != 0)
1406                                 goto skipping_dir_contents;
1407                         statret = -1;
1408                 }
1409                 if (dry_run && statret != 0) {
1410                         if (!dry_missing_dir)
1411                                 dry_missing_dir = file;
1412                         file->flags |= FLAG_MISSING_DIR;
1413                 }
1414                 init_stat_x(&real_sx);
1415                 real_sx.st = sx.st;
1416                 real_ret = statret;
1417                 if (file->flags & FLAG_DIR_CREATED)
1418                         statret = -1;
1419                 if (!preserve_perms) { /* See comment in non-dir code below. */
1420                         file->mode = dest_mode(file->mode, sx.st.st_mode,
1421                                                dflt_perms, statret == 0);
1422                 }
1423                 if (statret != 0 && basis_dir[0] != NULL) {
1424                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &sx,
1425                                               itemizing, code);
1426                         if (j == -2) {
1427                                 itemizing = 0;
1428                                 code = FNONE;
1429                                 statret = 1;
1430                         } else if (j >= 0) {
1431                                 statret = 1;
1432                                 fnamecmp = fnamecmpbuf;
1433                         }
1434                 }
1435                 if (itemizing && f_out != -1) {
1436                         itemize(fnamecmp, file, ndx, statret, &sx,
1437                                 statret ? ITEM_LOCAL_CHANGE : 0, 0, NULL);
1438                 }
1439                 if (real_ret != 0 && do_mkdir(fname,file->mode|added_perms) < 0 && errno != EEXIST) {
1440                         if (!relative_paths || errno != ENOENT
1441                          || make_path(fname, MKP_DROP_NAME | MKP_SKIP_SLASH) < 0
1442                          || (do_mkdir(fname, file->mode|added_perms) < 0 && errno != EEXIST)) {
1443                                 rsyserr(FERROR_XFER, errno,
1444                                         "recv_generator: mkdir %s failed",
1445                                         full_fname(fname));
1446                           skipping_dir_contents:
1447                                 rprintf(FERROR,
1448                                     "*** Skipping any contents from this failed directory ***\n");
1449                                 skip_dir = file;
1450                                 file->flags |= FLAG_MISSING_DIR;
1451                                 goto cleanup;
1452                         }
1453                 }
1454
1455 #ifdef SUPPORT_XATTRS
1456                 if (preserve_xattrs && statret == 1)
1457                         copy_xattrs(fnamecmpbuf, fname);
1458 #endif
1459                 if (set_file_attrs(fname, file, real_ret ? NULL : &real_sx, NULL, 0)
1460                     && INFO_GTE(NAME, 1) && code != FNONE && f_out != -1)
1461                         rprintf(code, "%s/\n", fname);
1462
1463                 /* We need to ensure that the dirs in the transfer have both
1464                  * readable and writable permissions during the time we are
1465                  * putting files within them.  This is then restored to the
1466                  * former permissions after the transfer is done. */
1467 #ifdef HAVE_CHMOD
1468                 if (!am_root && (file->mode & S_IRWXU) != S_IRWXU && dir_tweaking) {
1469                         mode_t mode = file->mode | S_IRWXU;
1470                         if (do_chmod(fname, mode) < 0) {
1471                                 rsyserr(FERROR_XFER, errno,
1472                                         "failed to modify permissions on %s",
1473                                         full_fname(fname));
1474                         }
1475                         need_retouch_dir_perms = 1;
1476                 }
1477 #endif
1478
1479                 if (real_ret != 0 && one_file_system)
1480                         real_sx.st.st_dev = filesystem_dev;
1481                 if (inc_recurse) {
1482                         if (one_file_system) {
1483                                 uint32 *devp = F_DIR_DEV_P(file);
1484                                 DEV_MAJOR(devp) = major(real_sx.st.st_dev);
1485                                 DEV_MINOR(devp) = minor(real_sx.st.st_dev);
1486                         }
1487                 }
1488                 else if (delete_during && f_out != -1 && !phase
1489                     && !(file->flags & FLAG_MISSING_DIR)) {
1490                         if (file->flags & FLAG_CONTENT_DIR)
1491                                 delete_in_dir(fname, file, &real_sx.st.st_dev);
1492                         else
1493                                 change_local_filter_dir(fname, strlen(fname), F_DEPTH(file));
1494                 }
1495                 prior_dir_file = file;
1496                 goto cleanup;
1497         }
1498
1499         /* If we're not preserving permissions, change the file-list's
1500          * mode based on the local permissions and some heuristics. */
1501         if (!preserve_perms) {
1502                 int exists = statret == 0 && !S_ISDIR(sx.st.st_mode);
1503                 file->mode = dest_mode(file->mode, sx.st.st_mode, dflt_perms,
1504                                        exists);
1505         }
1506
1507 #ifdef SUPPORT_HARD_LINKS
1508         if (preserve_hard_links && F_HLINK_NOT_FIRST(file)
1509          && hard_link_check(file, ndx, fname, statret, &sx, itemizing, code))
1510                 goto cleanup;
1511 #endif
1512
1513         if (preserve_links && S_ISLNK(file->mode)) {
1514 #ifdef SUPPORT_LINKS
1515                 const char *sl = F_SYMLINK(file);
1516                 if (safe_symlinks && unsafe_symlink(sl, fname)) {
1517                         if (INFO_GTE(NAME, 1)) {
1518                                 if (solo_file) {
1519                                         /* fname contains the destination path, but we
1520                                          * want to report the source path. */
1521                                         fname = f_name(file, NULL);
1522                                 }
1523                                 rprintf(FINFO,
1524                                         "ignoring unsafe symlink \"%s\" -> \"%s\"\n",
1525                                         fname, sl);
1526                         }
1527                         goto cleanup;
1528                 }
1529                 if (statret == 0) {
1530                         char lnk[MAXPATHLEN];
1531                         int len;
1532
1533                         if (S_ISLNK(sx.st.st_mode)
1534                          && (len = do_readlink(fname, lnk, MAXPATHLEN-1)) > 0
1535                          && strncmp(lnk, sl, len) == 0 && sl[len] == '\0') {
1536                                 /* The link is pointing to the right place. */
1537                                 set_file_attrs(fname, file, &sx, NULL, maybe_ATTRS_REPORT);
1538                                 if (itemizing)
1539                                         itemize(fname, file, ndx, 0, &sx, 0, 0, NULL);
1540 #ifdef SUPPORT_HARD_LINKS
1541                                 if (preserve_hard_links && F_IS_HLINKED(file))
1542                                         finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
1543 #endif
1544                                 if (remove_source_files == 1)
1545                                         goto return_with_success;
1546                                 goto cleanup;
1547                         }
1548                 } else if (basis_dir[0] != NULL) {
1549                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &sx,
1550                                               itemizing, code);
1551                         if (j == -2) {
1552 #ifndef CAN_HARDLINK_SYMLINK
1553                                 if (link_dest) {
1554                                         /* Resort to --copy-dest behavior. */
1555                                 } else
1556 #endif
1557                                 if (!copy_dest)
1558                                         goto cleanup;
1559                                 itemizing = 0;
1560                                 code = FNONE;
1561                         } else if (j >= 0) {
1562                                 statret = 1;
1563                                 fnamecmp = fnamecmpbuf;
1564                         }
1565                 }
1566                 if (atomic_create(file, fname, sl, NULL, MAKEDEV(0, 0), &sx, statret == 0 ? DEL_FOR_SYMLINK : 0)) {
1567                         set_file_attrs(fname, file, NULL, NULL, 0);
1568                         if (itemizing) {
1569                                 if (statret == 0 && !S_ISLNK(sx.st.st_mode))
1570                                         statret = -1;
1571                                 itemize(fnamecmp, file, ndx, statret, &sx,
1572                                         ITEM_LOCAL_CHANGE|ITEM_REPORT_CHANGE, 0, NULL);
1573                         }
1574                         if (code != FNONE && INFO_GTE(NAME, 1))
1575                                 rprintf(code, "%s -> %s\n", fname, sl);
1576 #ifdef SUPPORT_HARD_LINKS
1577                         if (preserve_hard_links && F_IS_HLINKED(file))
1578                                 finish_hard_link(file, fname, ndx, NULL, itemizing, code, -1);
1579 #endif
1580                         /* This does not check remove_source_files == 1
1581                          * because this is one of the items that the old
1582                          * --remove-sent-files option would remove. */
1583                         if (remove_source_files)
1584                                 goto return_with_success;
1585                 }
1586 #endif
1587                 goto cleanup;
1588         }
1589
1590         if ((am_root && preserve_devices && IS_DEVICE(file->mode))
1591          || (preserve_specials && IS_SPECIAL(file->mode))) {
1592                 dev_t rdev;
1593                 int del_for_flag = 0;
1594                 if (IS_DEVICE(file->mode)) {
1595                         uint32 *devp = F_RDEV_P(file);
1596                         rdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
1597                 } else
1598                         rdev = 0;
1599                 if (statret == 0) {
1600                         if (IS_DEVICE(file->mode)) {
1601                                 if (!IS_DEVICE(sx.st.st_mode))
1602                                         statret = -1;
1603                                 del_for_flag = DEL_FOR_DEVICE;
1604                         } else {
1605                                 if (!IS_SPECIAL(sx.st.st_mode))
1606                                         statret = -1;
1607                                 del_for_flag = DEL_FOR_SPECIAL;
1608                         }
1609                         if (statret == 0
1610                          && BITS_EQUAL(sx.st.st_mode, file->mode, _S_IFMT)
1611                          && (IS_SPECIAL(sx.st.st_mode) || sx.st.st_rdev == rdev)) {
1612                                 /* The device or special file is identical. */
1613                                 set_file_attrs(fname, file, &sx, NULL, maybe_ATTRS_REPORT);
1614                                 if (itemizing)
1615                                         itemize(fname, file, ndx, 0, &sx, 0, 0, NULL);
1616 #ifdef SUPPORT_HARD_LINKS
1617                                 if (preserve_hard_links && F_IS_HLINKED(file))
1618                                         finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
1619 #endif
1620                                 if (remove_source_files == 1)
1621                                         goto return_with_success;
1622                                 goto cleanup;
1623                         }
1624                 } else if (basis_dir[0] != NULL) {
1625                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &sx,
1626                                               itemizing, code);
1627                         if (j == -2) {
1628 #ifndef CAN_HARDLINK_SPECIAL
1629                                 if (link_dest) {
1630                                         /* Resort to --copy-dest behavior. */
1631                                 } else
1632 #endif
1633                                 if (!copy_dest)
1634                                         goto cleanup;
1635                                 itemizing = 0;
1636                                 code = FNONE;
1637                         } else if (j >= 0) {
1638                                 statret = 1;
1639                                 fnamecmp = fnamecmpbuf;
1640                         }
1641                 }
1642                 if (DEBUG_GTE(GENR, 1)) {
1643                         rprintf(FINFO, "mknod(%s, 0%o, [%ld,%ld])\n",
1644                                 fname, (int)file->mode,
1645                                 (long)major(rdev), (long)minor(rdev));
1646                 }
1647                 if (atomic_create(file, fname, NULL, NULL, rdev, &sx, del_for_flag)) {
1648                         set_file_attrs(fname, file, NULL, NULL, 0);
1649                         if (itemizing) {
1650                                 itemize(fnamecmp, file, ndx, statret, &sx,
1651                                         ITEM_LOCAL_CHANGE|ITEM_REPORT_CHANGE, 0, NULL);
1652                         }
1653                         if (code != FNONE && INFO_GTE(NAME, 1))
1654                                 rprintf(code, "%s\n", fname);
1655 #ifdef SUPPORT_HARD_LINKS
1656                         if (preserve_hard_links && F_IS_HLINKED(file))
1657                                 finish_hard_link(file, fname, ndx, NULL, itemizing, code, -1);
1658 #endif
1659                         if (remove_source_files == 1)
1660                                 goto return_with_success;
1661                 }
1662                 goto cleanup;
1663         }
1664
1665         if (!S_ISREG(file->mode)) {
1666                 if (solo_file)
1667                         fname = f_name(file, NULL);
1668                 rprintf(FINFO, "skipping non-regular file \"%s\"\n", fname);
1669                 goto cleanup;
1670         }
1671
1672         if (max_size >= 0 && F_LENGTH(file) > max_size) {
1673                 if (INFO_GTE(SKIP, 1)) {
1674                         if (solo_file)
1675                                 fname = f_name(file, NULL);
1676                         rprintf(FINFO, "%s is over max-size\n", fname);
1677                 }
1678                 goto cleanup;
1679         }
1680         if (min_size >= 0 && F_LENGTH(file) < min_size) {
1681                 if (INFO_GTE(SKIP, 1)) {
1682                         if (solo_file)
1683                                 fname = f_name(file, NULL);
1684                         rprintf(FINFO, "%s is under min-size\n", fname);
1685                 }
1686                 goto cleanup;
1687         }
1688
1689         if (update_only > 0 && statret == 0 && file->modtime - sx.st.st_mtime <= modify_window) {
1690                 if (INFO_GTE(SKIP, 1))
1691                         rprintf(FINFO, "%s is newer\n", fname);
1692 #ifdef SUPPORT_HARD_LINKS
1693                 if (F_IS_HLINKED(file))
1694                         handle_skipped_hlink(file, itemizing, code, f_out);
1695 #endif
1696                 goto cleanup;
1697         }
1698
1699         fnamecmp_type = FNAMECMP_FNAME;
1700
1701         if (statret == 0 && !(S_ISREG(sx.st.st_mode) || (write_devices && IS_DEVICE(sx.st.st_mode)))) {
1702                 if (delete_item(fname, sx.st.st_mode, del_opts | DEL_FOR_FILE) != 0)
1703                         goto cleanup;
1704                 statret = -1;
1705                 stat_errno = ENOENT;
1706         }
1707
1708         if (basis_dir[0] != NULL && (statret != 0 || !copy_dest)) {
1709                 int j = try_dests_reg(file, fname, ndx, fnamecmpbuf, &sx,
1710                                       statret == 0, itemizing, code);
1711                 if (j == -2) {
1712                         if (remove_source_files == 1)
1713                                 goto return_with_success;
1714                         goto cleanup;
1715                 }
1716                 if (j >= 0) {
1717                         fnamecmp = fnamecmpbuf;
1718                         fnamecmp_type = j;
1719                         statret = 0;
1720                 }
1721         }
1722
1723         init_stat_x(&real_sx);
1724         real_sx.st = sx.st; /* Don't copy xattr/acl pointers, as they would free wrong. */
1725         real_ret = statret;
1726
1727         if (partial_dir && (partialptr = partial_dir_fname(fname)) != NULL
1728             && link_stat(partialptr, &partial_st, 0) == 0
1729             && S_ISREG(partial_st.st_mode)) {
1730                 if (statret != 0)
1731                         goto prepare_to_open;
1732         } else
1733                 partialptr = NULL;
1734
1735         if (statret != 0 && fuzzy_basis) {
1736                 if (need_fuzzy_dirlist && S_ISREG(file->mode)) {
1737                         const char *dn = file->dirname ? file->dirname : ".";
1738                         int i;
1739                         strlcpy(fnamecmpbuf, dn, sizeof fnamecmpbuf);
1740                         for (i = 0; i < fuzzy_basis; i++) {
1741                                 if (i && pathjoin(fnamecmpbuf, MAXPATHLEN, basis_dir[i-1], dn) >= MAXPATHLEN)
1742                                         continue;
1743                                 fuzzy_dirlist[i] = get_dirlist(fnamecmpbuf, -1, GDL_IGNORE_FILTER_RULES | GDL_PERHAPS_DIR);
1744                                 if (fuzzy_dirlist[i] && fuzzy_dirlist[i]->used == 0) {
1745                                         flist_free(fuzzy_dirlist[i]);
1746                                         fuzzy_dirlist[i] = NULL;
1747                                 }
1748                         }
1749                         need_fuzzy_dirlist = 0;
1750                 }
1751
1752                 /* Sets fnamecmp_type to FNAMECMP_FUZZY or above. */
1753                 fuzzy_file = find_fuzzy(file, fuzzy_dirlist, &fnamecmp_type);
1754                 if (fuzzy_file) {
1755                         f_name(fuzzy_file, fnamecmpbuf);
1756                         if (DEBUG_GTE(FUZZY, 1)) {
1757                                 rprintf(FINFO, "fuzzy basis selected for %s: %s\n",
1758                                         fname, fnamecmpbuf);
1759                         }
1760                         sx.st.st_size = F_LENGTH(fuzzy_file);
1761                         statret = 0;
1762                         fnamecmp = fnamecmpbuf;
1763                 }
1764         }
1765
1766         if (statret != 0) {
1767 #ifdef SUPPORT_HARD_LINKS
1768                 if (preserve_hard_links && F_HLINK_NOT_LAST(file)) {
1769                         cur_flist->in_progress++;
1770                         goto cleanup;
1771                 }
1772 #endif
1773                 if (stat_errno == ENOENT)
1774                         goto notify_others;
1775                 rsyserr(FERROR_XFER, stat_errno, "recv_generator: failed to stat %s",
1776                         full_fname(fname));
1777                 goto cleanup;
1778         }
1779
1780         if (fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
1781                 ;
1782         else if (fnamecmp_type >= FNAMECMP_FUZZY)
1783                 ;
1784         else if (unchanged_file(fnamecmp, file, &sx.st)) {
1785                 if (partialptr) {
1786                         do_unlink(partialptr);
1787                         handle_partial_dir(partialptr, PDIR_DELETE);
1788                 }
1789                 set_file_attrs(fname, file, &sx, NULL, maybe_ATTRS_REPORT | maybe_ATTRS_ACCURATE_TIME);
1790                 if (itemizing)
1791                         itemize(fnamecmp, file, ndx, statret, &sx, 0, 0, NULL);
1792 #ifdef SUPPORT_HARD_LINKS
1793                 if (preserve_hard_links && F_IS_HLINKED(file))
1794                         finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
1795 #endif
1796                 if (remove_source_files != 1)
1797                         goto cleanup;
1798           return_with_success:
1799                 if (!dry_run)
1800                         send_msg_int(MSG_SUCCESS, ndx);
1801                 goto cleanup;
1802         }
1803
1804         if (append_mode > 0 && sx.st.st_size >= F_LENGTH(file)) {
1805 #ifdef SUPPORT_HARD_LINKS
1806                 if (F_IS_HLINKED(file))
1807                         handle_skipped_hlink(file, itemizing, code, f_out);
1808 #endif
1809                 goto cleanup;
1810         }
1811
1812   prepare_to_open:
1813         if (partialptr) {
1814                 sx.st = partial_st;
1815                 fnamecmp = partialptr;
1816                 fnamecmp_type = FNAMECMP_PARTIAL_DIR;
1817                 statret = 0;
1818         }
1819
1820         if (!do_xfers)
1821                 goto notify_others;
1822
1823         if (read_batch || whole_file) {
1824                 if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) {
1825                         if (!(backupptr = get_backup_name(fname)))
1826                                 goto cleanup;
1827                         if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS)))
1828                                 goto pretend_missing;
1829                         if (copy_file(fname, backupptr, -1, back_file->mode) < 0) {
1830                                 unmake_file(back_file);
1831                                 back_file = NULL;
1832                                 goto cleanup;
1833                         }
1834                 }
1835                 goto notify_others;
1836         }
1837
1838         if (fuzzy_dirlist[0]) {
1839                 int j = flist_find(fuzzy_dirlist[0], file);
1840                 if (j >= 0) /* don't use changing file as future fuzzy basis */
1841                         fuzzy_dirlist[0]->files[j]->flags |= FLAG_FILE_SENT;
1842         }
1843
1844         /* open the file */
1845         if ((fd = do_open(fnamecmp, O_RDONLY, 0)) < 0) {
1846                 rsyserr(FERROR, errno, "failed to open %s, continuing",
1847                         full_fname(fnamecmp));
1848           pretend_missing:
1849                 /* pretend the file didn't exist */
1850 #ifdef SUPPORT_HARD_LINKS
1851                 if (preserve_hard_links && F_HLINK_NOT_LAST(file)) {
1852                         cur_flist->in_progress++;
1853                         goto cleanup;
1854                 }
1855 #endif
1856                 statret = real_ret = -1;
1857                 goto notify_others;
1858         }
1859
1860         if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) {
1861                 if (!(backupptr = get_backup_name(fname))) {
1862                         close(fd);
1863                         goto cleanup;
1864                 }
1865                 if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) {
1866                         close(fd);
1867                         goto pretend_missing;
1868                 }
1869                 if (robust_unlink(backupptr) && errno != ENOENT) {
1870                         rsyserr(FERROR_XFER, errno, "unlink %s",
1871                                 full_fname(backupptr));
1872                         unmake_file(back_file);
1873                         back_file = NULL;
1874                         close(fd);
1875                         goto cleanup;
1876                 }
1877                 if ((f_copy = do_open(backupptr, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) {
1878                         rsyserr(FERROR_XFER, errno, "open %s", full_fname(backupptr));
1879                         unmake_file(back_file);
1880                         back_file = NULL;
1881                         close(fd);
1882                         goto cleanup;
1883                 }
1884                 fnamecmp_type = FNAMECMP_BACKUP;
1885         }
1886
1887         if (DEBUG_GTE(DELTASUM, 3)) {
1888                 rprintf(FINFO, "gen mapped %s of size %s\n",
1889                         fnamecmp, big_num(sx.st.st_size));
1890         }
1891
1892         if (DEBUG_GTE(DELTASUM, 2))
1893                 rprintf(FINFO, "generating and sending sums for %d\n", ndx);
1894
1895   notify_others:
1896         if (remove_source_files && !delay_updates && !phase && !dry_run)
1897                 increment_active_files(ndx, itemizing, code);
1898         if (inc_recurse && (!dry_run || write_batch < 0))
1899                 cur_flist->in_progress++;
1900 #ifdef SUPPORT_HARD_LINKS
1901         if (preserve_hard_links && F_IS_HLINKED(file))
1902                 file->flags |= FLAG_FILE_SENT;
1903 #endif
1904         write_ndx(f_out, ndx);
1905         if (itemizing) {
1906                 int iflags = ITEM_TRANSFER;
1907                 if (always_checksum > 0)
1908                         iflags |= ITEM_REPORT_CHANGE;
1909                 if (fnamecmp_type != FNAMECMP_FNAME)
1910                         iflags |= ITEM_BASIS_TYPE_FOLLOWS;
1911                 if (fnamecmp_type >= FNAMECMP_FUZZY)
1912                         iflags |= ITEM_XNAME_FOLLOWS;
1913                 itemize(fnamecmp, file, -1, real_ret, &real_sx, iflags, fnamecmp_type,
1914                         fuzzy_file ? fuzzy_file->basename : NULL);
1915                 free_stat_x(&real_sx);
1916         }
1917
1918         if (!do_xfers) {
1919 #ifdef SUPPORT_HARD_LINKS
1920                 if (preserve_hard_links && F_IS_HLINKED(file))
1921                         finish_hard_link(file, fname, ndx, &sx.st, itemizing, code, -1);
1922 #endif
1923                 goto cleanup;
1924         }
1925         if (read_batch)
1926                 goto cleanup;
1927
1928         if (statret != 0 || whole_file)
1929                 write_sum_head(f_out, NULL);
1930         else if (sx.st.st_size <= 0) {
1931                 write_sum_head(f_out, NULL);
1932                 close(fd);
1933         } else {
1934                 if (generate_and_send_sums(fd, sx.st.st_size, f_out, f_copy) < 0) {
1935                         rprintf(FWARNING,
1936                             "WARNING: file is too large for checksum sending: %s\n",
1937                             fnamecmp);
1938                         write_sum_head(f_out, NULL);
1939                 }
1940                 close(fd);
1941         }
1942
1943   cleanup:
1944         if (back_file) {
1945                 int save_preserve_xattrs = preserve_xattrs;
1946                 if (f_copy >= 0)
1947                         close(f_copy);
1948 #ifdef SUPPORT_XATTRS
1949                 if (preserve_xattrs) {
1950                         copy_xattrs(fname, backupptr);
1951                         preserve_xattrs = 0;
1952                 }
1953 #endif
1954                 set_file_attrs(backupptr, back_file, NULL, NULL, 0);
1955                 preserve_xattrs = save_preserve_xattrs;
1956                 if (INFO_GTE(BACKUP, 1)) {
1957                         rprintf(FINFO, "backed up %s to %s\n",
1958                                 fname, backupptr);
1959                 }
1960                 unmake_file(back_file);
1961         }
1962
1963         free_stat_x(&sx);
1964 }
1965
1966 /* If we are replacing an existing hard link, symlink, device, or special file,
1967  * create a temp-name item and rename it into place.  A symlimk specifies slnk,
1968  * a hard link specifies hlnk, otherwise we create a device based on rdev.
1969  * Specify 0 for the del_for_flag if there is not a file to replace.  This
1970  * returns 1 on success and 0 on failure. */
1971 int atomic_create(struct file_struct *file, char *fname, const char *slnk, const char *hlnk,
1972                   dev_t rdev, stat_x *sxp, int del_for_flag)
1973 {
1974         char tmpname[MAXPATHLEN];
1975         const char *create_name;
1976         int skip_atomic, dir_in_the_way = del_for_flag && S_ISDIR(sxp->st.st_mode);
1977
1978         if (!del_for_flag || dir_in_the_way || tmpdir || !get_tmpname(tmpname, fname, True))
1979                 skip_atomic = 1;
1980         else
1981                 skip_atomic = 0;
1982
1983         if (del_for_flag) {
1984                 if (make_backups > 0 && !dir_in_the_way) {
1985                         if (!make_backup(fname, skip_atomic))
1986                                 return 0;
1987                 } else if (skip_atomic) {
1988                         int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0;
1989                         if (delete_item(fname, sxp->st.st_mode, del_opts | del_for_flag) != 0)
1990                                 return 0;
1991                 }
1992         }
1993
1994         create_name = skip_atomic ? fname : tmpname;
1995
1996         if (slnk) {
1997 #ifdef SUPPORT_LINKS
1998                 if (do_symlink(slnk, create_name) < 0) {
1999                         rsyserr(FERROR_XFER, errno, "symlink %s -> \"%s\" failed",
2000                                 full_fname(create_name), slnk);
2001                         return 0;
2002                 }
2003 #else
2004                 return 0;
2005 #endif
2006         } else if (hlnk) {
2007 #ifdef SUPPORT_HARD_LINKS
2008                 if (!hard_link_one(file, create_name, hlnk, 0))
2009                         return 0;
2010 #else
2011                 return 0;
2012 #endif
2013         } else {
2014                 if (do_mknod(create_name, file->mode, rdev) < 0) {
2015                         rsyserr(FERROR_XFER, errno, "mknod %s failed",
2016                                 full_fname(create_name));
2017                         return 0;
2018                 }
2019         }
2020
2021         if (!skip_atomic) {
2022                 if (do_rename(tmpname, fname) < 0) {
2023                         rsyserr(FERROR_XFER, errno, "rename %s -> \"%s\" failed",
2024                                 full_fname(tmpname), full_fname(fname));
2025                         do_unlink(tmpname);
2026                         return 0;
2027                 }
2028         }
2029
2030         return 1;
2031 }
2032
2033 #ifdef SUPPORT_HARD_LINKS
2034 static void handle_skipped_hlink(struct file_struct *file, int itemizing,
2035                                  enum logcode code, int f_out)
2036 {
2037         char fbuf[MAXPATHLEN];
2038         int new_last_ndx;
2039         struct file_list *save_flist = cur_flist;
2040
2041         /* If we skip the last item in a chain of links and there was a
2042          * prior non-skipped hard-link waiting to finish, finish it now. */
2043         if ((new_last_ndx = skip_hard_link(file, &cur_flist)) < 0)
2044                 return;
2045
2046         file = cur_flist->files[new_last_ndx - cur_flist->ndx_start];
2047         cur_flist->in_progress--; /* undo prior increment */
2048         f_name(file, fbuf);
2049         recv_generator(fbuf, file, new_last_ndx, itemizing, code, f_out);
2050
2051         cur_flist = save_flist;
2052 }
2053 #endif
2054
2055 static void touch_up_dirs(struct file_list *flist, int ndx)
2056 {
2057         static int counter = 0;
2058         struct file_struct *file;
2059         char *fname;
2060         BOOL fix_dir_perms;
2061         int i, start, end;
2062
2063         if (ndx < 0) {
2064                 start = 0;
2065                 end = flist->used - 1;
2066         } else
2067                 start = end = ndx;
2068
2069         /* Fix any directory permissions that were modified during the
2070          * transfer and/or re-set any tweaked modified-time values. */
2071         for (i = start; i <= end; i++, counter++) {
2072                 file = flist->files[i];
2073                 if (!F_IS_ACTIVE(file))
2074                         continue;
2075                 if (!S_ISDIR(file->mode)
2076                  || (!implied_dirs && file->flags & FLAG_IMPLIED_DIR))
2077                         continue;
2078                 if (DEBUG_GTE(TIME, 2)) {
2079                         fname = f_name(file, NULL);
2080                         rprintf(FINFO, "touch_up_dirs: %s (%d)\n",
2081                                 NS(fname), i);
2082                 }
2083                 /* Be sure not to retouch permissions with --fake-super. */
2084                 fix_dir_perms = !am_root && !(file->mode & S_IWUSR);
2085                 if (file->flags & FLAG_MISSING_DIR || !(need_retouch_dir_times || fix_dir_perms))
2086                         continue;
2087                 fname = f_name(file, NULL);
2088                 if (fix_dir_perms)
2089                         do_chmod(fname, file->mode);
2090                 if (need_retouch_dir_times) {
2091                         STRUCT_STAT st;
2092                         if (link_stat(fname, &st, 0) == 0 && mtime_differs(&st, file)) {
2093                                 st.st_mtime = file->modtime;
2094 #ifdef ST_MTIME_NSEC
2095                                 st.ST_MTIME_NSEC = F_MOD_NSEC_or_0(file);
2096 #endif
2097                                 set_times(fname, &st);
2098                         }
2099                 }
2100                 if (counter >= loopchk_limit) {
2101                         if (allowed_lull)
2102                                 maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
2103                         else
2104                                 maybe_flush_socket(0);
2105                         counter = 0;
2106                 }
2107         }
2108 }
2109
2110 void check_for_finished_files(int itemizing, enum logcode code, int check_redo)
2111 {
2112         struct file_struct *file;
2113         struct file_list *flist;
2114         char fbuf[MAXPATHLEN];
2115         int ndx;
2116
2117         while (1) {
2118 #ifdef SUPPORT_HARD_LINKS
2119                 if (preserve_hard_links && (ndx = get_hlink_num()) != -1) {
2120                         int send_failed = (ndx == -2);
2121                         if (send_failed)
2122                                 ndx = get_hlink_num();
2123                         flist = flist_for_ndx(ndx, "check_for_finished_files.1");
2124                         file = flist->files[ndx - flist->ndx_start];
2125                         assert(file->flags & FLAG_HLINKED);
2126                         if (send_failed)
2127                                 handle_skipped_hlink(file, itemizing, code, sock_f_out);
2128                         else
2129                                 finish_hard_link(file, f_name(file, fbuf), ndx, NULL, itemizing, code, -1);
2130                         flist->in_progress--;
2131                         continue;
2132                 }
2133 #endif
2134
2135                 if (check_redo && (ndx = get_redo_num()) != -1) {
2136                         OFF_T save_max_size = max_size;
2137                         OFF_T save_min_size = min_size;
2138                         csum_length = SUM_LENGTH;
2139                         max_size = -1;
2140                         min_size = -1;
2141                         ignore_existing = -ignore_existing;
2142                         ignore_non_existing = -ignore_non_existing;
2143                         update_only = -update_only;
2144                         always_checksum = -always_checksum;
2145                         size_only = -size_only;
2146                         append_mode = -append_mode;
2147                         make_backups = -make_backups; /* avoid dup backup w/inplace */
2148                         ignore_times++;
2149
2150                         flist = cur_flist;
2151                         cur_flist = flist_for_ndx(ndx, "check_for_finished_files.2");
2152
2153                         file = cur_flist->files[ndx - cur_flist->ndx_start];
2154                         if (solo_file)
2155                                 strlcpy(fbuf, solo_file, sizeof fbuf);
2156                         else
2157                                 f_name(file, fbuf);
2158                         recv_generator(fbuf, file, ndx, itemizing, code, sock_f_out);
2159                         cur_flist->to_redo--;
2160
2161                         cur_flist = flist;
2162
2163                         csum_length = SHORT_SUM_LENGTH;
2164                         max_size = save_max_size;
2165                         min_size = save_min_size;
2166                         ignore_existing = -ignore_existing;
2167                         ignore_non_existing = -ignore_non_existing;
2168                         update_only = -update_only;
2169                         always_checksum = -always_checksum;
2170                         size_only = -size_only;
2171                         append_mode = -append_mode;
2172                         make_backups = -make_backups;
2173                         ignore_times--;
2174                         continue;
2175                 }
2176
2177                 if (cur_flist == first_flist)
2178                         break;
2179
2180                 /* We only get here if inc_recurse is enabled. */
2181                 if (first_flist->in_progress || first_flist->to_redo)
2182                         break;
2183
2184                 write_ndx(sock_f_out, NDX_DONE);
2185                 if (!read_batch && !flist_eof) {
2186                         int old_total = 0;
2187                         for (flist = first_flist; flist != cur_flist; flist = flist->next)
2188                                 old_total += flist->used;
2189                         maybe_flush_socket(!flist_eof && file_total - old_total < MIN_FILECNT_LOOKAHEAD/2);
2190                 }
2191
2192                 if (delete_during == 2 || !dir_tweaking) {
2193                         /* Skip directory touch-up. */
2194                 } else if (first_flist->parent_ndx >= 0)
2195                         touch_up_dirs(dir_flist, first_flist->parent_ndx);
2196
2197                 flist_free(first_flist); /* updates first_flist */
2198         }
2199 }
2200
2201 void generate_files(int f_out, const char *local_name)
2202 {
2203         int i, ndx, next_loopchk = 0;
2204         char fbuf[MAXPATHLEN];
2205         int itemizing;
2206         enum logcode code;
2207         int save_info_flist = info_levels[INFO_FLIST];
2208         int save_info_progress = info_levels[INFO_PROGRESS];
2209
2210         if (protocol_version >= 29) {
2211                 itemizing = 1;
2212                 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
2213                 code = logfile_format_has_i ? FNONE : FLOG;
2214         } else if (am_daemon) {
2215                 itemizing = logfile_format_has_i && do_xfers;
2216                 maybe_ATTRS_REPORT = ATTRS_REPORT;
2217                 code = itemizing || !do_xfers ? FCLIENT : FINFO;
2218         } else if (!am_server) {
2219                 itemizing = stdout_format_has_i;
2220                 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
2221                 code = itemizing ? FNONE : FINFO;
2222         } else {
2223                 itemizing = 0;
2224                 maybe_ATTRS_REPORT = ATTRS_REPORT;
2225                 code = FINFO;
2226         }
2227         solo_file = local_name;
2228         dir_tweaking = !(list_only || solo_file || dry_run);
2229         need_retouch_dir_times = preserve_times & PRESERVE_DIR_TIMES;
2230         loopchk_limit = allowed_lull ? allowed_lull * 5 : 200;
2231         symlink_timeset_failed_flags = ITEM_REPORT_TIME
2232             | (protocol_version >= 30 || !am_server ? ITEM_REPORT_TIMEFAIL : 0);
2233         implied_dirs_are_missing = relative_paths && !implied_dirs && protocol_version < 30;
2234
2235         if (DEBUG_GTE(GENR, 1))
2236                 rprintf(FINFO, "generator starting pid=%d\n", (int)getpid());
2237
2238         if (delete_before && !solo_file && cur_flist->used > 0)
2239                 do_delete_pass();
2240         if (delete_during == 2) {
2241                 deldelay_size = BIGPATHBUFLEN * 4;
2242                 deldelay_buf = new_array(char, deldelay_size);
2243                 if (!deldelay_buf)
2244                         out_of_memory("delete-delay");
2245         }
2246         info_levels[INFO_FLIST] = info_levels[INFO_PROGRESS] = 0;
2247
2248         if (append_mode > 0 || whole_file < 0)
2249                 whole_file = 0;
2250         if (DEBUG_GTE(FLIST, 1)) {
2251                 rprintf(FINFO, "delta-transmission %s\n",
2252                         whole_file
2253                         ? "disabled for local transfer or --whole-file"
2254                         : "enabled");
2255         }
2256
2257         dflt_perms = (ACCESSPERMS & ~orig_umask);
2258
2259         do {
2260 #ifdef SUPPORT_HARD_LINKS
2261                 if (preserve_hard_links && inc_recurse) {
2262                         while (!flist_eof && file_total < MIN_FILECNT_LOOKAHEAD/2)
2263                                 wait_for_receiver();
2264                 }
2265 #endif
2266
2267                 if (inc_recurse && cur_flist->parent_ndx >= 0) {
2268                         struct file_struct *fp = dir_flist->files[cur_flist->parent_ndx];
2269                         if (solo_file)
2270                                 strlcpy(fbuf, solo_file, sizeof fbuf);
2271                         else
2272                                 f_name(fp, fbuf);
2273                         ndx = cur_flist->ndx_start - 1;
2274                         recv_generator(fbuf, fp, ndx, itemizing, code, f_out);
2275                         if (delete_during && dry_run < 2 && !list_only
2276                          && !(fp->flags & FLAG_MISSING_DIR)) {
2277                                 if (fp->flags & FLAG_CONTENT_DIR) {
2278                                         dev_t dirdev;
2279                                         if (one_file_system) {
2280                                                 uint32 *devp = F_DIR_DEV_P(fp);
2281                                                 dirdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
2282                                         } else
2283                                                 dirdev = MAKEDEV(0, 0);
2284                                         delete_in_dir(fbuf, fp, &dirdev);
2285                                 } else
2286                                         change_local_filter_dir(fbuf, strlen(fbuf), F_DEPTH(fp));
2287                         }
2288                 }
2289                 for (i = cur_flist->low; i <= cur_flist->high; i++) {
2290                         struct file_struct *file = cur_flist->sorted[i];
2291
2292                         if (!F_IS_ACTIVE(file))
2293                                 continue;
2294
2295                         if (unsort_ndx)
2296                                 ndx = F_NDX(file);
2297                         else
2298                                 ndx = i + cur_flist->ndx_start;
2299
2300                         if (solo_file)
2301                                 strlcpy(fbuf, solo_file, sizeof fbuf);
2302                         else
2303                                 f_name(file, fbuf);
2304                         recv_generator(fbuf, file, ndx, itemizing, code, f_out);
2305
2306                         check_for_finished_files(itemizing, code, 0);
2307
2308                         if (i + cur_flist->ndx_start >= next_loopchk) {
2309                                 if (allowed_lull)
2310                                         maybe_send_keepalive(time(NULL), MSK_ALLOW_FLUSH);
2311                                 else
2312                                         maybe_flush_socket(0);
2313                                 next_loopchk += loopchk_limit;
2314                         }
2315                 }
2316
2317                 if (!inc_recurse) {
2318                         write_ndx(f_out, NDX_DONE);
2319                         break;
2320                 }
2321
2322                 while (1) {
2323                         check_for_finished_files(itemizing, code, 1);
2324                         if (cur_flist->next || flist_eof)
2325                                 break;
2326                         wait_for_receiver();
2327                 }
2328         } while ((cur_flist = cur_flist->next) != NULL);
2329
2330         if (delete_during)
2331                 delete_in_dir(NULL, NULL, &dev_zero);
2332         phase++;
2333         if (DEBUG_GTE(GENR, 1))
2334                 rprintf(FINFO, "generate_files phase=%d\n", phase);
2335
2336         while (1) {
2337                 check_for_finished_files(itemizing, code, 1);
2338                 if (msgdone_cnt)
2339                         break;
2340                 wait_for_receiver();
2341         }
2342
2343         phase++;
2344         if (DEBUG_GTE(GENR, 1))
2345                 rprintf(FINFO, "generate_files phase=%d\n", phase);
2346
2347         write_ndx(f_out, NDX_DONE);
2348
2349         /* Reduce round-trip lag-time for a useless delay-updates phase. */
2350         if (protocol_version >= 29 && EARLY_DELAY_DONE_MSG())
2351                 write_ndx(f_out, NDX_DONE);
2352
2353         if (protocol_version >= 31 && EARLY_DELETE_DONE_MSG()) {
2354                 if ((INFO_GTE(STATS, 2) && (delete_mode || force_delete)) || read_batch)
2355                         write_del_stats(f_out);
2356                 if (EARLY_DELAY_DONE_MSG()) /* Can't send this before delay */
2357                         write_ndx(f_out, NDX_DONE);
2358         }
2359
2360         /* Read MSG_DONE for the redo phase (and any prior messages). */
2361         while (1) {
2362                 check_for_finished_files(itemizing, code, 0);
2363                 if (msgdone_cnt > 1)
2364                         break;
2365                 wait_for_receiver();
2366         }
2367
2368         if (protocol_version >= 29) {
2369                 phase++;
2370                 if (DEBUG_GTE(GENR, 1))
2371                         rprintf(FINFO, "generate_files phase=%d\n", phase);
2372                 if (!EARLY_DELAY_DONE_MSG()) {
2373                         write_ndx(f_out, NDX_DONE);
2374                         if (protocol_version >= 31 && EARLY_DELETE_DONE_MSG())
2375                                 write_ndx(f_out, NDX_DONE);
2376                 }
2377                 /* Read MSG_DONE for delay-updates phase & prior messages. */
2378                 while (msgdone_cnt == 2)
2379                         wait_for_receiver();
2380         }
2381
2382         info_levels[INFO_FLIST] = save_info_flist;
2383         info_levels[INFO_PROGRESS] = save_info_progress;
2384
2385         if (delete_during == 2)
2386                 do_delayed_deletions(fbuf);
2387         if (delete_after && !solo_file && file_total > 0)
2388                 do_delete_pass();
2389
2390         if (max_delete >= 0 && skipped_deletes) {
2391                 rprintf(FWARNING,
2392                         "Deletions stopped due to --max-delete limit (%d skipped)\n",
2393                         skipped_deletes);
2394                 io_error |= IOERR_DEL_LIMIT;
2395         }
2396
2397         if (protocol_version >= 31) {
2398                 if (!EARLY_DELETE_DONE_MSG()) {
2399                         if (INFO_GTE(STATS, 2) || read_batch)
2400                                 write_del_stats(f_out);
2401                         write_ndx(f_out, NDX_DONE);
2402                 }
2403
2404                 /* Read MSG_DONE for late-delete phase & prior messages. */
2405                 while (msgdone_cnt == 3)
2406                         wait_for_receiver();
2407         }
2408
2409         if ((need_retouch_dir_perms || need_retouch_dir_times)
2410          && dir_tweaking && (!inc_recurse || delete_during == 2))
2411                 touch_up_dirs(dir_flist, -1);
2412
2413         if (DEBUG_GTE(GENR, 1))
2414                 rprintf(FINFO, "generate_files finished\n");
2415 }