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