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