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