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