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