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