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