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