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