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