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