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