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