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