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