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