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