Changed two more references to "st" to "real_st" in the dir-handling
[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, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
22  */
23
24 #include "rsync.h"
25
26 extern int verbose;
27 extern int dry_run;
28 extern int do_xfers;
29 extern int stdout_format_has_i;
30 extern int logfile_format_has_i;
31 extern int am_root;
32 extern int am_server;
33 extern int am_daemon;
34 extern int do_progress;
35 extern int relative_paths;
36 extern int implied_dirs;
37 extern int keep_dirlinks;
38 extern int preserve_links;
39 extern int preserve_devices;
40 extern int preserve_specials;
41 extern int preserve_hard_links;
42 extern int preserve_perms;
43 extern int preserve_uid;
44 extern int preserve_gid;
45 extern int preserve_times;
46 extern int omit_dir_times;
47 extern int delete_mode;
48 extern int delete_before;
49 extern int delete_during;
50 extern int delete_after;
51 extern int module_id;
52 extern int ignore_errors;
53 extern int remove_source_files;
54 extern int delay_updates;
55 extern int update_only;
56 extern int ignore_existing;
57 extern int ignore_non_existing;
58 extern int inplace;
59 extern int append_mode;
60 extern int make_backups;
61 extern int csum_length;
62 extern int ignore_times;
63 extern int size_only;
64 extern OFF_T max_size;
65 extern OFF_T min_size;
66 extern int io_error;
67 extern int allowed_lull;
68 extern int sock_f_out;
69 extern int ignore_timeout;
70 extern int protocol_version;
71 extern int fuzzy_basis;
72 extern int always_checksum;
73 extern int checksum_len;
74 extern char *partial_dir;
75 extern char *basis_dir[];
76 extern int compare_dest;
77 extern int copy_dest;
78 extern int link_dest;
79 extern int whole_file;
80 extern int list_only;
81 extern int new_root_dir;
82 extern int read_batch;
83 extern int safe_symlinks;
84 extern long block_size; /* "long" because popt can't set an int32. */
85 extern int max_delete;
86 extern int force_delete;
87 extern int one_file_system;
88 extern struct stats stats;
89 extern dev_t filesystem_dev;
90 extern char *backup_dir;
91 extern char *backup_suffix;
92 extern int backup_suffix_len;
93 extern struct file_list *the_file_list;
94 extern struct filter_list_struct server_filter_list;
95
96 static int deletion_count = 0; /* used to implement --max-delete */
97
98 /* For calling delete_file() */
99 #define DEL_FORCE_RECURSE       (1<<1) /* recurse even w/o --force */
100 #define DEL_TERSE               (1<<3)
101
102 enum nonregtype {
103     TYPE_DIR, TYPE_SPECIAL, TYPE_DEVICE, TYPE_SYMLINK
104 };
105
106 static int is_backup_file(char *fn)
107 {
108         int k = strlen(fn) - backup_suffix_len;
109         return k > 0 && strcmp(fn+k, backup_suffix) == 0;
110 }
111
112
113 /* Delete a file or directory.  If DEL_FORCE_RECURSE is set in the flags, or if
114  * force_delete is set, this will delete recursively.
115  *
116  * Note that fname must point to a MAXPATHLEN buffer if the mode indicates it's
117  * a directory! (The buffer is used for recursion, but returned unchanged.)
118  */
119 static int delete_item(char *fname, int mode, int flags)
120 {
121         struct file_list *dirlist;
122         int j, dlen, zap_dir, ok;
123         unsigned remainder;
124         void *save_filters;
125         char *p;
126
127         if (!S_ISDIR(mode)) {
128                 if (max_delete && ++deletion_count > max_delete)
129                         return 0;
130                 if (make_backups && (backup_dir || !is_backup_file(fname)))
131                         ok = make_backup(fname);
132                 else
133                         ok = robust_unlink(fname) == 0;
134                 if (ok) {
135                         if (!(flags & DEL_TERSE))
136                                 log_delete(fname, mode);
137                         return 0;
138                 }
139                 if (errno == ENOENT) {
140                         deletion_count--;
141                         return 0;
142                 }
143                 rsyserr(FERROR, errno, "delete_file: unlink %s failed",
144                         full_fname(fname));
145                 return -1;
146         }
147
148         zap_dir = flags & DEL_FORCE_RECURSE || force_delete;
149         if ((max_delete && ++deletion_count > max_delete)
150             || (dry_run && zap_dir)) {
151                 ok = 0;
152                 errno = ENOTEMPTY;
153         } else if (make_backups && !backup_dir && !is_backup_file(fname)
154             && !(flags & DEL_FORCE_RECURSE))
155                 ok = make_backup(fname);
156         else
157                 ok = do_rmdir(fname) == 0;
158         if (ok) {
159                 if (!(flags & DEL_TERSE))
160                         log_delete(fname, mode);
161                 return 0;
162         }
163         if (errno == ENOENT) {
164                 deletion_count--;
165                 return 0;
166         }
167         if (!zap_dir) {
168                 rsyserr(FERROR, errno, "delete_file: rmdir %s failed",
169                         full_fname(fname));
170                 return -1;
171         }
172         flags |= DEL_FORCE_RECURSE; /* mark subdir dels as not "in the way" */
173         deletion_count--;
174
175         dlen = strlen(fname);
176         save_filters = push_local_filters(fname, dlen);
177
178         dirlist = get_dirlist(fname, dlen, 0);
179
180         p = fname + dlen;
181         if (dlen != 1 || *fname != '/')
182                 *p++ = '/';
183         remainder = MAXPATHLEN - (p - fname);
184
185         for (j = dirlist->count; j--; ) {
186                 struct file_struct *fp = dirlist->files[j];
187
188                 if (fp->flags & FLAG_MOUNT_POINT)
189                         continue;
190
191                 strlcpy(p, fp->basename, remainder);
192                 delete_item(fname, fp->mode, flags & ~DEL_TERSE);
193         }
194         flist_free(dirlist);
195
196         fname[dlen] = '\0';
197
198         pop_local_filters(save_filters);
199
200         if (max_delete && ++deletion_count > max_delete)
201                 return 0;
202
203         if (do_rmdir(fname) == 0) {
204                 if (!(flags & DEL_TERSE))
205                         log_delete(fname, mode);
206         } else if (errno != ENOTEMPTY && errno != EEXIST && errno != ENOENT) {
207                 rsyserr(FERROR, errno, "delete_file: rmdir %s failed",
208                         full_fname(fname));
209                 return -1;
210         }
211
212         return 0;
213 }
214
215
216 /* This function is used to implement per-directory deletion, and is used by
217  * all the --delete-WHEN options.  Note that the fbuf pointer must point to a
218  * MAXPATHLEN buffer with the name of the directory in it (the functions we
219  * call will append names onto the end, but the old dir value will be restored
220  * on exit). */
221 static void delete_in_dir(struct file_list *flist, char *fbuf,
222                           struct file_struct *file, STRUCT_STAT *stp)
223 {
224         static int min_depth = MAXPATHLEN, cur_depth = -1;
225         static void *filt_array[MAXPATHLEN/2+1];
226         static int already_warned = 0;
227         struct file_list *dirlist;
228         char delbuf[MAXPATHLEN];
229         int dlen, i;
230
231         if (!flist) {
232                 while (cur_depth >= min_depth)
233                         pop_local_filters(filt_array[cur_depth--]);
234                 min_depth = MAXPATHLEN;
235                 cur_depth = -1;
236                 return;
237         }
238
239         if (verbose > 2)
240                 rprintf(FINFO, "delete_in_dir(%s)\n", fbuf);
241
242         if (allowed_lull)
243                 maybe_send_keepalive();
244
245         if (file->dir.depth >= MAXPATHLEN/2+1)
246                 return; /* Impossible... */
247
248         if (io_error && !(lp_ignore_errors(module_id) || ignore_errors)) {
249                 if (already_warned)
250                         return;
251                 rprintf(FINFO,
252                         "IO error encountered -- skipping file deletion\n");
253                 already_warned = 1;
254                 return;
255         }
256
257         while (cur_depth >= file->dir.depth && cur_depth >= min_depth)
258                 pop_local_filters(filt_array[cur_depth--]);
259         cur_depth = file->dir.depth;
260         if (min_depth > cur_depth)
261                 min_depth = cur_depth;
262         dlen = strlen(fbuf);
263         filt_array[cur_depth] = push_local_filters(fbuf, dlen);
264
265         if (one_file_system) {
266                 if (file->flags & FLAG_TOP_DIR)
267                         filesystem_dev = stp->st_dev;
268                 else if (filesystem_dev != stp->st_dev)
269                         return;
270         }
271
272         dirlist = get_dirlist(fbuf, dlen, 0);
273
274         /* If an item in dirlist is not found in flist, delete it
275          * from the filesystem. */
276         for (i = dirlist->count; i--; ) {
277                 struct file_struct *fp = dirlist->files[i];
278                 if (!fp->basename || fp->flags & FLAG_MOUNT_POINT)
279                         continue;
280                 if (flist_find(flist, fp) < 0) {
281                         f_name(fp, delbuf);
282                         delete_item(delbuf, fp->mode, DEL_FORCE_RECURSE);
283                 }
284         }
285
286         flist_free(dirlist);
287 }
288
289 /* This deletes any files on the receiving side that are not present on the
290  * sending side.  This is used by --delete-before and --delete-after. */
291 static void do_delete_pass(struct file_list *flist)
292 {
293         char fbuf[MAXPATHLEN];
294         STRUCT_STAT st;
295         int j;
296
297         /* dry_run is incremented when the destination doesn't exist yet. */
298         if (dry_run > 1 || list_only)
299                 return;
300
301         for (j = 0; j < flist->count; j++) {
302                 struct file_struct *file = flist->files[j];
303
304                 if (!(file->flags & FLAG_DEL_HERE))
305                         continue;
306
307                 f_name(file, fbuf);
308                 if (verbose > 1 && file->flags & FLAG_TOP_DIR)
309                         rprintf(FINFO, "deleting in %s\n", fbuf);
310
311                 if (link_stat(fbuf, &st, keep_dirlinks) < 0
312                  || !S_ISDIR(st.st_mode))
313                         continue;
314
315                 delete_in_dir(flist, fbuf, file, &st);
316         }
317         delete_in_dir(NULL, NULL, NULL, NULL);
318
319         if (do_progress && !am_server)
320                 rprintf(FINFO, "                    \r");
321 }
322
323 int unchanged_attrs(struct file_struct *file, STRUCT_STAT *st)
324 {
325         if (preserve_perms
326          && (st->st_mode & CHMOD_BITS) != (file->mode & CHMOD_BITS))
327                 return 0;
328
329         if (am_root && preserve_uid && st->st_uid != file->uid)
330                 return 0;
331
332         if (preserve_gid && file->gid != GID_NONE && st->st_gid != file->gid)
333                 return 0;
334
335         return 1;
336 }
337
338 void itemize(struct file_struct *file, int ndx, int statret, STRUCT_STAT *st,
339              int32 iflags, uchar fnamecmp_type, char *xname)
340 {
341         if (statret >= 0) { /* A from-dest-dir statret can == 1! */
342                 int keep_time = !preserve_times ? 0
343                     : S_ISDIR(file->mode) ? !omit_dir_times
344                     : !S_ISLNK(file->mode);
345
346                 if (S_ISREG(file->mode) && file->length != st->st_size)
347                         iflags |= ITEM_REPORT_SIZE;
348                 if ((iflags & (ITEM_TRANSFER|ITEM_LOCAL_CHANGE) && !keep_time
349                   && !(iflags & ITEM_MATCHED)
350                   && (!(iflags & ITEM_XNAME_FOLLOWS) || *xname))
351                  || (keep_time && cmp_time(file->modtime, st->st_mtime) != 0))
352                         iflags |= ITEM_REPORT_TIME;
353                 if ((file->mode & CHMOD_BITS) != (st->st_mode & CHMOD_BITS))
354                         iflags |= ITEM_REPORT_PERMS;
355                 if (preserve_uid && am_root && file->uid != st->st_uid)
356                         iflags |= ITEM_REPORT_OWNER;
357                 if (preserve_gid && file->gid != GID_NONE
358                     && st->st_gid != file->gid)
359                         iflags |= ITEM_REPORT_GROUP;
360         } else
361                 iflags |= ITEM_IS_NEW;
362
363         iflags &= 0xffff;
364         if ((iflags & SIGNIFICANT_ITEM_FLAGS || verbose > 1
365           || stdout_format_has_i > 1 || (xname && *xname)) && !read_batch) {
366                 if (protocol_version >= 29) {
367                         if (ndx >= 0)
368                                 write_int(sock_f_out, ndx);
369                         write_shortint(sock_f_out, iflags);
370                         if (iflags & ITEM_BASIS_TYPE_FOLLOWS)
371                                 write_byte(sock_f_out, fnamecmp_type);
372                         if (iflags & ITEM_XNAME_FOLLOWS)
373                                 write_vstring(sock_f_out, xname, strlen(xname));
374                 } else if (ndx >= 0) {
375                         enum logcode code = logfile_format_has_i ? FINFO : FCLIENT;
376                         log_item(code, file, &stats, iflags, xname);
377                 }
378         }
379 }
380
381
382 /* Perform our quick-check heuristic for determining if a file is unchanged. */
383 int unchanged_file(char *fn, struct file_struct *file, STRUCT_STAT *st)
384 {
385         if (st->st_size != file->length)
386                 return 0;
387
388         /* if always checksum is set then we use the checksum instead
389            of the file time to determine whether to sync */
390         if (always_checksum && S_ISREG(st->st_mode)) {
391                 char sum[MD4_SUM_LENGTH];
392                 file_checksum(fn, sum, st->st_size);
393                 return memcmp(sum, file->u.sum, checksum_len) == 0;
394         }
395
396         if (size_only)
397                 return 1;
398
399         if (ignore_times)
400                 return 0;
401
402         return cmp_time(st->st_mtime, file->modtime) == 0;
403 }
404
405
406 /*
407  * set (initialize) the size entries in the per-file sum_struct
408  * calculating dynamic block and checksum sizes.
409  *
410  * This is only called from generate_and_send_sums() but is a separate
411  * function to encapsulate the logic.
412  *
413  * The block size is a rounded square root of file length.
414  *
415  * The checksum size is determined according to:
416  *     blocksum_bits = BLOCKSUM_BIAS + 2*log2(file_len) - log2(block_len)
417  * provided by Donovan Baarda which gives a probability of rsync
418  * algorithm corrupting data and falling back using the whole md4
419  * checksums.
420  *
421  * This might be made one of several selectable heuristics.
422  */
423 static void sum_sizes_sqroot(struct sum_struct *sum, int64 len)
424 {
425         int32 blength;
426         int s2length;
427
428         if (block_size)
429                 blength = block_size;
430         else if (len <= BLOCK_SIZE * BLOCK_SIZE)
431                 blength = BLOCK_SIZE;
432         else {
433                 int32 c;
434                 int64 l;
435                 int cnt;
436                 for (c = 1, l = len, cnt = 0; l >>= 2; c <<= 1, cnt++) {}
437                 if (cnt >= 31 || c >= MAX_BLOCK_SIZE)
438                         blength = MAX_BLOCK_SIZE;
439                 else {
440                     blength = 0;
441                     do {
442                             blength |= c;
443                             if (len < (int64)blength * blength)
444                                     blength &= ~c;
445                             c >>= 1;
446                     } while (c >= 8);   /* round to multiple of 8 */
447                     blength = MAX(blength, BLOCK_SIZE);
448                 }
449         }
450
451         if (protocol_version < 27) {
452                 s2length = csum_length;
453         } else if (csum_length == SUM_LENGTH) {
454                 s2length = SUM_LENGTH;
455         } else {
456                 int32 c;
457                 int64 l;
458                 int b = BLOCKSUM_BIAS;
459                 for (l = len; l >>= 1; b += 2) {}
460                 for (c = blength; (c >>= 1) && b; b--) {}
461                 /* add a bit, subtract rollsum, round up. */
462                 s2length = (b + 1 - 32 + 7) / 8; /* --optimize in compiler-- */
463                 s2length = MAX(s2length, csum_length);
464                 s2length = MIN(s2length, SUM_LENGTH);
465         }
466
467         sum->flength    = len;
468         sum->blength    = blength;
469         sum->s2length   = s2length;
470         sum->remainder  = len % blength;
471         sum->count      = len / blength + (sum->remainder != 0);
472
473         if (sum->count && verbose > 2) {
474                 rprintf(FINFO,
475                         "count=%.0f rem=%ld blength=%ld s2length=%d flength=%.0f\n",
476                         (double)sum->count, (long)sum->remainder, (long)sum->blength,
477                         sum->s2length, (double)sum->flength);
478         }
479 }
480
481
482 /*
483  * Generate and send a stream of signatures/checksums that describe a buffer
484  *
485  * Generate approximately one checksum every block_len bytes.
486  */
487 static void generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy)
488 {
489         int32 i;
490         struct map_struct *mapbuf;
491         struct sum_struct sum;
492         OFF_T offset = 0;
493
494         sum_sizes_sqroot(&sum, len);
495         write_sum_head(f_out, &sum);
496
497         if (append_mode > 0 && f_copy < 0)
498                 return;
499
500         if (len > 0)
501                 mapbuf = map_file(fd, len, MAX_MAP_SIZE, sum.blength);
502         else
503                 mapbuf = NULL;
504
505         for (i = 0; i < sum.count; i++) {
506                 int32 n1 = (int32)MIN(len, (OFF_T)sum.blength);
507                 char *map = map_ptr(mapbuf, offset, n1);
508                 char sum2[SUM_LENGTH];
509                 uint32 sum1;
510
511                 len -= n1;
512                 offset += n1;
513
514                 if (f_copy >= 0) {
515                         full_write(f_copy, map, n1);
516                         if (append_mode > 0)
517                                 continue;
518                 }
519
520                 sum1 = get_checksum1(map, n1);
521                 get_checksum2(map, n1, sum2);
522
523                 if (verbose > 3) {
524                         rprintf(FINFO,
525                                 "chunk[%.0f] offset=%.0f len=%ld sum1=%08lx\n",
526                                 (double)i, (double)offset - n1, (long)n1,
527                                 (unsigned long)sum1);
528                 }
529                 write_int(f_out, sum1);
530                 write_buf(f_out, sum2, sum.s2length);
531         }
532
533         if (mapbuf)
534                 unmap_file(mapbuf);
535 }
536
537
538 /* Try to find a filename in the same dir as "fname" with a similar name. */
539 static int find_fuzzy(struct file_struct *file, struct file_list *dirlist)
540 {
541         int fname_len, fname_suf_len;
542         const char *fname_suf, *fname = file->basename;
543         uint32 lowest_dist = 25 << 16; /* ignore a distance greater than 25 */
544         int j, lowest_j = -1;
545
546         fname_len = strlen(fname);
547         fname_suf = find_filename_suffix(fname, fname_len, &fname_suf_len);
548
549         for (j = 0; j < dirlist->count; j++) {
550                 struct file_struct *fp = dirlist->files[j];
551                 const char *suf, *name;
552                 int len, suf_len;
553                 uint32 dist;
554
555                 if (!S_ISREG(fp->mode) || !fp->length
556                     || fp->flags & FLAG_NO_FUZZY)
557                         continue;
558
559                 name = fp->basename;
560
561                 if (fp->length == file->length
562                     && cmp_time(fp->modtime, file->modtime) == 0) {
563                         if (verbose > 4) {
564                                 rprintf(FINFO,
565                                         "fuzzy size/modtime match for %s\n",
566                                         name);
567                         }
568                         return j;
569                 }
570
571                 len = strlen(name);
572                 suf = find_filename_suffix(name, len, &suf_len);
573
574                 dist = fuzzy_distance(name, len, fname, fname_len);
575                 /* Add some extra weight to how well the suffixes match. */
576                 dist += fuzzy_distance(suf, suf_len, fname_suf, fname_suf_len)
577                       * 10;
578                 if (verbose > 4) {
579                         rprintf(FINFO, "fuzzy distance for %s = %d.%05d\n",
580                                 name, (int)(dist>>16), (int)(dist&0xFFFF));
581                 }
582                 if (dist <= lowest_dist) {
583                         lowest_dist = dist;
584                         lowest_j = j;
585                 }
586         }
587
588         return lowest_j;
589 }
590
591 void check_for_finished_hlinks(int itemizing, enum logcode code)
592 {
593         struct file_struct *file;
594         int ndx;
595
596         while ((ndx = get_hlink_num()) != -1) {
597                 if (ndx < 0 || ndx >= the_file_list->count)
598                         continue;
599
600                 file = the_file_list->files[ndx];
601                 if (!file->link_u.links)
602                         continue;
603
604                 hard_link_cluster(file, ndx, itemizing, code);
605         }
606 }
607
608 /* This is only called for regular files.  We return -2 if we've finished
609  * handling the file, -1 if no dest-linking occurred, or a non-negative
610  * value if we found an alternate basis file. */
611 static int try_dests_reg(struct file_struct *file, char *fname, int ndx,
612                          char *cmpbuf, STRUCT_STAT *stp, int itemizing,
613                          int maybe_ATTRS_REPORT, enum logcode code)
614 {
615         int best_match = -1;
616         int match_level = 0;
617         int j = 0;
618
619         do {
620                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
621                 if (link_stat(cmpbuf, stp, 0) < 0 || !S_ISREG(stp->st_mode))
622                         continue;
623                 switch (match_level) {
624                 case 0:
625                         best_match = j;
626                         match_level = 1;
627                         /* FALL THROUGH */
628                 case 1:
629                         if (!unchanged_file(cmpbuf, file, stp))
630                                 continue;
631                         best_match = j;
632                         match_level = 2;
633                         /* FALL THROUGH */
634                 case 2:
635                         if (!unchanged_attrs(file, stp))
636                                 continue;
637                         if (always_checksum && preserve_times
638                          && cmp_time(stp->st_mtime, file->modtime))
639                                 continue;
640                         best_match = j;
641                         match_level = 3;
642                         break;
643                 }
644                 break;
645         } while (basis_dir[++j] != NULL);
646
647         if (!match_level)
648                 return -1;
649
650         if (j != best_match) {
651                 j = best_match;
652                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
653                 if (link_stat(cmpbuf, stp, 0) < 0)
654                         return -1;
655         }
656
657         if (match_level == 3 && !copy_dest) {
658 #ifdef SUPPORT_HARD_LINKS
659                 if (link_dest) {
660                         int i = itemizing && (verbose > 1 || stdout_format_has_i > 1);
661                         if (hard_link_one(file, ndx, fname, 0, stp,
662                                           cmpbuf, 1, i, code) < 0)
663                                 goto try_a_copy;
664                         if (preserve_hard_links && file->link_u.links) {
665                                 if (dry_run)
666                                         file->link_u.links->link_dest_used = j + 1;
667                                 hard_link_cluster(file, ndx, itemizing, code);
668                         }
669                 } else
670 #endif
671                 if (itemizing)
672                         itemize(file, ndx, 0, stp, 0, 0, NULL);
673                 if (verbose > 1 && maybe_ATTRS_REPORT) {
674                         rprintf(FCLIENT, "%s is uptodate\n", fname);
675                 }
676                 return -2;
677         }
678
679         if (match_level >= 2) {
680           try_a_copy: /* Copy the file locally. */
681                 if (copy_file(cmpbuf, fname, file->mode) < 0) {
682                         if (verbose) {
683                                 rsyserr(FINFO, errno, "copy_file %s => %s",
684                                         full_fname(cmpbuf), fname);
685                         }
686                         return -1;
687                 }
688                 if (itemizing)
689                         itemize(file, ndx, 0, stp, ITEM_LOCAL_CHANGE, 0, NULL);
690                 set_file_attrs(fname, file, NULL, 0);
691                 if (maybe_ATTRS_REPORT
692                  && ((!itemizing && verbose && match_level == 2)
693                   || (verbose > 1 && match_level == 3))) {
694                         code = match_level == 3 ? FCLIENT : FINFO;
695                         rprintf(code, "%s%s\n", fname,
696                                 match_level == 3 ? " is uptodate" : "");
697                 }
698                 if (preserve_hard_links && file->link_u.links)
699                         hard_link_cluster(file, ndx, itemizing, code);
700                 return -2;
701         }
702
703         return FNAMECMP_BASIS_DIR_LOW + j;
704 }
705
706 /* This is only called for non-regular files.  We return -2 if we've finished
707  * handling the file, or -1 if no dest-linking occurred, or a non-negative
708  * value if we found an alternate basis file. */
709 static int try_dests_non(struct file_struct *file, char *fname, int ndx,
710                          char *cmpbuf, STRUCT_STAT *stp, int itemizing,
711                          int maybe_ATTRS_REPORT, enum logcode code)
712 {
713         char lnk[MAXPATHLEN];
714         int best_match = -1;
715         int match_level = 0;
716         enum nonregtype type;
717         int len, j = 0;
718
719 #ifndef SUPPORT_LINKS
720         if (S_ISLNK(file->mode))
721                 return -1;
722 #endif
723         if (S_ISDIR(file->mode)) {
724                 type = TYPE_DIR;
725         } else if (IS_SPECIAL(file->mode))
726                 type = TYPE_SPECIAL;
727         else if (IS_DEVICE(file->mode))
728                 type = TYPE_DEVICE;
729 #ifdef SUPPORT_LINKS
730         else if (S_ISLNK(file->mode))
731                 type = TYPE_SYMLINK;
732 #endif
733         else {
734                 rprintf(FERROR,
735                         "internal: try_dests_non() called with invalid mode (%o)\n",
736                         (int)file->mode);
737                 exit_cleanup(RERR_UNSUPPORTED);
738         }
739
740         do {
741                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
742                 if (link_stat(cmpbuf, stp, 0) < 0)
743                         continue;
744                 switch (type) {
745                 case TYPE_DIR:
746                         if (!S_ISDIR(stp->st_mode))
747                                 continue;
748                         break;
749                 case TYPE_SPECIAL:
750                         if (!IS_SPECIAL(stp->st_mode))
751                                 continue;
752                         break;
753                 case TYPE_DEVICE:
754                         if (!IS_DEVICE(stp->st_mode))
755                                 continue;
756                         break;
757 #ifdef SUPPORT_LINKS
758                 case TYPE_SYMLINK:
759                         if (!S_ISLNK(stp->st_mode))
760                                 continue;
761                         break;
762 #endif
763                 }
764                 if (match_level < 1) {
765                         match_level = 1;
766                         best_match = j;
767                 }
768                 switch (type) {
769                 case TYPE_DIR:
770                         break;
771                 case TYPE_SPECIAL:
772                 case TYPE_DEVICE:
773                         if (stp->st_rdev != file->u.rdev)
774                                 continue;
775                         break;
776 #ifdef SUPPORT_LINKS
777                 case TYPE_SYMLINK:
778                         if ((len = readlink(cmpbuf, lnk, MAXPATHLEN-1)) <= 0)
779                                 continue;
780                         lnk[len] = '\0';
781                         if (strcmp(lnk, file->u.link) != 0)
782                                 continue;
783                         break;
784 #endif
785                 }
786                 if (match_level < 2) {
787                         match_level = 2;
788                         best_match = j;
789                 }
790                 if (unchanged_attrs(file, stp)) {
791                         match_level = 3;
792                         best_match = j;
793                         break;
794                 }
795         } while (basis_dir[++j] != NULL);
796
797         if (!match_level)
798                 return -1;
799
800         if (j != best_match) {
801                 j = best_match;
802                 pathjoin(cmpbuf, MAXPATHLEN, basis_dir[j], fname);
803                 if (link_stat(cmpbuf, stp, 0) < 0)
804                         return -1;
805         }
806
807         if (match_level == 3) {
808 #ifdef SUPPORT_HARD_LINKS
809                 if (link_dest
810 #ifndef CAN_HARDLINK_SYMLINK
811                  && !S_ISLNK(file->mode)
812 #endif
813 #ifndef CAN_HARDLINK_SPECIAL
814                  && !IS_SPECIAL(file->mode) && !IS_DEVICE(file->mode)
815 #endif
816                  && !S_ISDIR(file->mode)) {
817                         if (do_link(cmpbuf, fname) < 0) {
818                                 rsyserr(FERROR, errno,
819                                         "failed to hard-link %s with %s",
820                                         cmpbuf, fname);
821                                 return j;
822                         }
823                         if (preserve_hard_links && file->link_u.links)
824                                 hard_link_cluster(file, ndx, itemizing, code);
825                 } else
826 #endif
827                         match_level = 2;
828                 if (itemizing && stdout_format_has_i
829                  && (verbose > 1 || stdout_format_has_i > 1)) {
830                         int chg = compare_dest && type != TYPE_DIR ? 0
831                             : ITEM_LOCAL_CHANGE
832                              + (match_level == 3 ? ITEM_XNAME_FOLLOWS : 0);
833                         char *lp = match_level == 3 ? "" : NULL;
834                         itemize(file, ndx, 0, stp, chg + ITEM_MATCHED, 0, lp);
835                 }
836                 if (verbose > 1 && maybe_ATTRS_REPORT) {
837                         rprintf(FCLIENT, "%s%s is uptodate\n",
838                                 fname, type == TYPE_DIR ? "/" : "");
839                 }
840                 return -2;
841         }
842
843         return j;
844 }
845
846 static int phase = 0;
847
848 /* Acts on the_file_list->file's ndx'th item, whose name is fname.  If a dir,
849  * make sure it exists, and has the right permissions/timestamp info.  For
850  * all other non-regular files (symlinks, etc.) we create them here.  For
851  * regular files that have changed, we try to find a basis file and then
852  * start sending checksums.
853  *
854  * When fname is non-null, it must point to a MAXPATHLEN buffer!
855  *
856  * Note that f_out is set to -1 when doing final directory-permission and
857  * modification-time repair. */
858 static void recv_generator(char *fname, struct file_struct *file, int ndx,
859                            int itemizing, int maybe_ATTRS_REPORT,
860                            enum logcode code, int f_out)
861 {
862         static int missing_below = -1, excluded_below = -1;
863         static char *parent_dirname = "";
864         static struct file_list *fuzzy_dirlist = NULL;
865         static int need_fuzzy_dirlist = 0;
866         struct file_struct *fuzzy_file = NULL;
867         int fd = -1, f_copy = -1;
868         STRUCT_STAT st, real_st, partial_st;
869         struct file_struct *back_file = NULL;
870         int statret, real_ret, stat_errno;
871         char *fnamecmp, *partialptr, *backupptr = NULL;
872         char fnamecmpbuf[MAXPATHLEN];
873         uchar fnamecmp_type;
874         int del_opts = DEL_TERSE | (delete_mode ? DEL_FORCE_RECURSE : 0);
875
876         if (list_only)
877                 return;
878
879         if (!fname) {
880                 if (fuzzy_dirlist) {
881                         flist_free(fuzzy_dirlist);
882                         fuzzy_dirlist = NULL;
883                 }
884                 if (missing_below >= 0) {
885                         if (dry_run)
886                                 dry_run--;
887                         missing_below = -1;
888                 }
889                 parent_dirname = "";
890                 return;
891         }
892
893         if (verbose > 2)
894                 rprintf(FINFO, "recv_generator(%s,%d)\n", fname, ndx);
895
896         if (server_filter_list.head) {
897                 if (excluded_below >= 0) {
898                         if (file->dir.depth > excluded_below)
899                                 goto skipping;
900                         excluded_below = -1;
901                 }
902                 if (check_filter(&server_filter_list, fname,
903                                  S_ISDIR(file->mode)) < 0) {
904                         if (S_ISDIR(file->mode))
905                                 excluded_below = file->dir.depth;
906                   skipping:
907                         if (verbose) {
908                                 rprintf(FINFO,
909                                         "skipping server-excluded file \"%s\"\n",
910                                         fname);
911                         }
912                         return;
913                 }
914         }
915
916         if (missing_below >= 0) {
917                 if (file->dir.depth <= missing_below) {
918                         if (dry_run)
919                                 dry_run--;
920                         missing_below = -1;
921                 } else if (!dry_run)
922                         return;
923         }
924         if (dry_run > 1) {
925                 statret = -1;
926                 stat_errno = ENOENT;
927         } else {
928                 char *dn = file->dirname ? file->dirname : ".";
929                 if (parent_dirname != dn && strcmp(parent_dirname, dn) != 0) {
930                         if (relative_paths && !implied_dirs
931                          && do_stat(dn, &st) < 0
932                          && create_directory_path(fname) < 0) {
933                                 rsyserr(FERROR, errno,
934                                         "recv_generator: mkdir %s failed",
935                                         full_fname(dn));
936                         }
937                         if (fuzzy_dirlist) {
938                                 flist_free(fuzzy_dirlist);
939                                 fuzzy_dirlist = NULL;
940                         }
941                         if (fuzzy_basis)
942                                 need_fuzzy_dirlist = 1;
943                 }
944                 parent_dirname = dn;
945
946                 if (need_fuzzy_dirlist && S_ISREG(file->mode)) {
947                         fuzzy_dirlist = get_dirlist(dn, -1, 1);
948                         need_fuzzy_dirlist = 0;
949                 }
950
951                 statret = link_stat(fname, &st,
952                                     keep_dirlinks && S_ISDIR(file->mode));
953                 stat_errno = errno;
954         }
955
956         if (ignore_non_existing && statret == -1 && stat_errno == ENOENT) {
957                 if (verbose > 1) {
958                         rprintf(FINFO, "not creating new %s \"%s\"\n",
959                                 S_ISDIR(file->mode) ? "directory" : "file",
960                                 fname);
961                 }
962                 return;
963         }
964
965         /* If we're not preserving permissions, change the file-list's
966          * mode based on the local permissions and some heuristics. */
967         if (!preserve_perms) {
968                 int exists = statret == 0
969                           && S_ISDIR(st.st_mode) == S_ISDIR(file->mode);
970                 file->mode = dest_mode(file->mode, st.st_mode, exists);
971         }
972
973         if (S_ISDIR(file->mode)) {
974                 /* The file to be received is a directory, so we need
975                  * to prepare appropriately.  If there is already a
976                  * file of that name and it is *not* a directory, then
977                  * we need to delete it.  If it doesn't exist, then
978                  * (perhaps recursively) create it. */
979                 if (statret == 0 && !S_ISDIR(st.st_mode)) {
980                         if (delete_item(fname, st.st_mode, del_opts) < 0)
981                                 return;
982                         statret = -1;
983                 }
984                 if (dry_run && statret != 0 && missing_below < 0) {
985                         missing_below = file->dir.depth;
986                         dry_run++;
987                 }
988                 real_ret = statret;
989                 real_st = st;
990                 if (new_root_dir) {
991                         if (*fname == '.' && fname[1] == '\0')
992                                 statret = -1;
993                         new_root_dir = 0;
994                 }
995                 if (statret != 0 && basis_dir[0] != NULL) {
996                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &st,
997                                               itemizing, maybe_ATTRS_REPORT, code);
998                         if (j == -2) {
999                                 itemizing = 0;
1000                                 code = FNONE;
1001                         } else if (j >= 0)
1002                                 statret = 1;
1003                 }
1004                 if (itemizing && f_out != -1) {
1005                         itemize(file, ndx, statret, &st,
1006                                 statret ? ITEM_LOCAL_CHANGE : 0, 0, NULL);
1007                 }
1008                 if (real_ret != 0 && do_mkdir(fname,file->mode) < 0 && errno != EEXIST) {
1009                         if (!relative_paths || errno != ENOENT
1010                             || create_directory_path(fname) < 0
1011                             || (do_mkdir(fname, file->mode) < 0 && errno != EEXIST)) {
1012                                 rsyserr(FERROR, errno,
1013                                         "recv_generator: mkdir %s failed",
1014                                         full_fname(fname));
1015                                 file->flags |= FLAG_MISSING;
1016                                 if (ndx+1 < the_file_list->count
1017                                  && the_file_list->files[ndx+1]->dir.depth > file->dir.depth) {
1018                                         rprintf(FERROR,
1019                                             "*** Skipping everything below this failed directory ***\n");
1020                                         missing_below = file->dir.depth;
1021                                 }
1022                                 return;
1023                         }
1024                 }
1025                 if (set_file_attrs(fname, file, real_ret ? NULL : &real_st, 0)
1026                     && verbose && code != FNONE && f_out != -1)
1027                         rprintf(code, "%s/\n", fname);
1028                 if (real_ret != 0 && one_file_system)
1029                         real_st.st_dev = filesystem_dev;
1030                 if (delete_during && f_out != -1 && !phase && dry_run < 2
1031                     && (file->flags & FLAG_DEL_HERE))
1032                         delete_in_dir(the_file_list, fname, file, &real_st);
1033                 return;
1034         }
1035
1036         if (preserve_hard_links && file->link_u.links
1037             && hard_link_check(file, ndx, fname, statret, &st,
1038                                itemizing, code, HL_CHECK_MASTER))
1039                 return;
1040
1041         if (preserve_links && S_ISLNK(file->mode)) {
1042 #ifdef SUPPORT_LINKS
1043                 if (safe_symlinks && unsafe_symlink(file->u.link, fname)) {
1044                         if (verbose) {
1045                                 if (the_file_list->count == 1)
1046                                         fname = f_name(file, NULL);
1047                                 rprintf(FINFO,
1048                                         "ignoring unsafe symlink %s -> \"%s\"\n",
1049                                         full_fname(fname), file->u.link);
1050                         }
1051                         return;
1052                 }
1053                 if (statret == 0) {
1054                         char lnk[MAXPATHLEN];
1055                         int len;
1056
1057                         if (!S_ISLNK(st.st_mode))
1058                                 statret = -1;
1059                         else if ((len = readlink(fname, lnk, MAXPATHLEN-1)) > 0
1060                               && strncmp(lnk, file->u.link, len) == 0
1061                               && file->u.link[len] == '\0') {
1062                                 /* The link is pointing to the right place. */
1063                                 if (itemizing)
1064                                         itemize(file, ndx, 0, &st, 0, 0, NULL);
1065                                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1066                                 if (preserve_hard_links && file->link_u.links)
1067                                         hard_link_cluster(file, ndx, itemizing, code);
1068                                 if (remove_source_files == 1)
1069                                         goto return_with_success;
1070                                 return;
1071                         }
1072                         /* Not the right symlink (or not a symlink), so
1073                          * delete it. */
1074                         if (delete_item(fname, st.st_mode, del_opts) < 0)
1075                                 return;
1076                 } else if (basis_dir[0] != NULL) {
1077                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &st,
1078                                               itemizing, maybe_ATTRS_REPORT, code);
1079                         if (j == -2) {
1080 #ifndef CAN_HARDLINK_SYMLINK
1081                                 if (link_dest) {
1082                                         /* Resort to --copy-dest behavior. */
1083                                 } else
1084 #endif
1085                                 if (!copy_dest)
1086                                         return;
1087                                 itemizing = 0;
1088                                 code = FNONE;
1089                         } else if (j >= 0)
1090                                 statret = 1;
1091                 }
1092                 if (preserve_hard_links && file->link_u.links
1093                     && hard_link_check(file, ndx, fname, -1, &st,
1094                                        itemizing, code, HL_SKIP))
1095                         return;
1096                 if (do_symlink(file->u.link, fname) != 0) {
1097                         rsyserr(FERROR, errno, "symlink %s -> \"%s\" failed",
1098                                 full_fname(fname), file->u.link);
1099                 } else {
1100                         set_file_attrs(fname, file, NULL, 0);
1101                         if (itemizing) {
1102                                 itemize(file, ndx, statret, &st,
1103                                         ITEM_LOCAL_CHANGE, 0, NULL);
1104                         }
1105                         if (code != FNONE && verbose)
1106                                 rprintf(code, "%s -> %s\n", fname, file->u.link);
1107                         if (preserve_hard_links && file->link_u.links)
1108                                 hard_link_cluster(file, ndx, itemizing, code);
1109                         /* This does not check remove_source_files == 1
1110                          * because this is one of the items that the old
1111                          * --remove-sent-files option would remove. */
1112                         if (remove_source_files)
1113                                 goto return_with_success;
1114                 }
1115 #endif
1116                 return;
1117         }
1118
1119         if ((am_root && preserve_devices && IS_DEVICE(file->mode))
1120          || (preserve_specials && IS_SPECIAL(file->mode))) {
1121                 if (statret == 0) {
1122                         if ((IS_DEVICE(file->mode) && !IS_DEVICE(st.st_mode))
1123                          || (IS_SPECIAL(file->mode) && !IS_SPECIAL(st.st_mode)))
1124                                 statret = -1;
1125                         else if ((st.st_mode & ~CHMOD_BITS) == (file->mode & ~CHMOD_BITS)
1126                               && st.st_rdev == file->u.rdev) {
1127                                 /* The device or special file is identical. */
1128                                 if (itemizing)
1129                                         itemize(file, ndx, 0, &st, 0, 0, NULL);
1130                                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1131                                 if (preserve_hard_links && file->link_u.links)
1132                                         hard_link_cluster(file, ndx, itemizing, code);
1133                                 if (remove_source_files == 1)
1134                                         goto return_with_success;
1135                                 return;
1136                         }
1137                         if (delete_item(fname, st.st_mode, del_opts) < 0)
1138                                 return;
1139                 } else if (basis_dir[0] != NULL) {
1140                         int j = try_dests_non(file, fname, ndx, fnamecmpbuf, &st,
1141                                               itemizing, maybe_ATTRS_REPORT, code);
1142                         if (j == -2) {
1143 #ifndef CAN_HARDLINK_SPECIAL
1144                                 if (link_dest) {
1145                                         /* Resort to --copy-dest behavior. */
1146                                 } else
1147 #endif
1148                                 if (!copy_dest)
1149                                         return;
1150                                 itemizing = 0;
1151                                 code = FNONE;
1152                         } else if (j >= 0)
1153                                 statret = 1;
1154                 }
1155                 if (preserve_hard_links && file->link_u.links
1156                     && hard_link_check(file, ndx, fname, -1, &st,
1157                                        itemizing, code, HL_SKIP))
1158                         return;
1159                 if (verbose > 2) {
1160                         rprintf(FINFO,"mknod(%s,0%o,0x%x)\n",
1161                                 fname, (int)file->mode, (int)file->u.rdev);
1162                 }
1163                 if (do_mknod(fname, file->mode, file->u.rdev) < 0) {
1164                         rsyserr(FERROR, errno, "mknod %s failed",
1165                                 full_fname(fname));
1166                 } else {
1167                         set_file_attrs(fname, file, NULL, 0);
1168                         if (itemizing) {
1169                                 itemize(file, ndx, statret, &st,
1170                                         ITEM_LOCAL_CHANGE, 0, NULL);
1171                         }
1172                         if (code != FNONE && verbose)
1173                                 rprintf(code, "%s\n", fname);
1174                         if (preserve_hard_links && file->link_u.links)
1175                                 hard_link_cluster(file, ndx, itemizing, code);
1176                         if (remove_source_files == 1)
1177                                 goto return_with_success;
1178                 }
1179                 return;
1180         }
1181
1182         if (!S_ISREG(file->mode)) {
1183                 if (the_file_list->count == 1)
1184                         fname = f_name(file, NULL);
1185                 rprintf(FINFO, "skipping non-regular file \"%s\"\n", fname);
1186                 return;
1187         }
1188
1189         if (max_size && file->length > max_size) {
1190                 if (verbose > 1) {
1191                         if (the_file_list->count == 1)
1192                                 fname = f_name(file, NULL);
1193                         rprintf(FINFO, "%s is over max-size\n", fname);
1194                 }
1195                 return;
1196         }
1197         if (min_size && file->length < min_size) {
1198                 if (verbose > 1) {
1199                         if (the_file_list->count == 1)
1200                                 fname = f_name(file, NULL);
1201                         rprintf(FINFO, "%s is under min-size\n", fname);
1202                 }
1203                 return;
1204         }
1205
1206         if (ignore_existing && statret == 0) {
1207                 if (verbose > 1)
1208                         rprintf(FINFO, "%s exists\n", fname);
1209                 return;
1210         }
1211
1212         if (update_only && statret == 0
1213             && cmp_time(st.st_mtime, file->modtime) > 0) {
1214                 if (verbose > 1)
1215                         rprintf(FINFO, "%s is newer\n", fname);
1216                 return;
1217         }
1218
1219         fnamecmp = fname;
1220         fnamecmp_type = FNAMECMP_FNAME;
1221
1222         if (statret == 0 && !S_ISREG(st.st_mode)) {
1223                 if (delete_item(fname, st.st_mode, del_opts) != 0)
1224                         return;
1225                 statret = -1;
1226                 stat_errno = ENOENT;
1227         }
1228
1229         if (statret != 0 && basis_dir[0] != NULL) {
1230                 int j = try_dests_reg(file, fname, ndx, fnamecmpbuf, &st,
1231                                       itemizing, maybe_ATTRS_REPORT, code);
1232                 if (j == -2) {
1233                         if (remove_source_files == 1)
1234                                 goto return_with_success;
1235                         return;
1236                 }
1237                 if (j >= 0) {
1238                         fnamecmp = fnamecmpbuf;
1239                         fnamecmp_type = j;
1240                         statret = 0;
1241                 }
1242         }
1243
1244         real_ret = statret;
1245         real_st = st;
1246
1247         if (partial_dir && (partialptr = partial_dir_fname(fname)) != NULL
1248             && link_stat(partialptr, &partial_st, 0) == 0
1249             && S_ISREG(partial_st.st_mode)) {
1250                 if (statret != 0)
1251                         goto prepare_to_open;
1252         } else
1253                 partialptr = NULL;
1254
1255         if (statret != 0 && fuzzy_dirlist && dry_run <= 1) {
1256                 int j = find_fuzzy(file, fuzzy_dirlist);
1257                 if (j >= 0) {
1258                         fuzzy_file = fuzzy_dirlist->files[j];
1259                         f_name(fuzzy_file, fnamecmpbuf);
1260                         if (verbose > 2) {
1261                                 rprintf(FINFO, "fuzzy basis selected for %s: %s\n",
1262                                         fname, fnamecmpbuf);
1263                         }
1264                         st.st_size = fuzzy_file->length;
1265                         statret = 0;
1266                         fnamecmp = fnamecmpbuf;
1267                         fnamecmp_type = FNAMECMP_FUZZY;
1268                 }
1269         }
1270
1271         if (statret != 0) {
1272                 if (preserve_hard_links && file->link_u.links
1273                     && hard_link_check(file, ndx, fname, statret, &st,
1274                                        itemizing, code, HL_SKIP))
1275                         return;
1276                 if (stat_errno == ENOENT)
1277                         goto notify_others;
1278                 rsyserr(FERROR, stat_errno, "recv_generator: failed to stat %s",
1279                         full_fname(fname));
1280                 return;
1281         }
1282
1283         if (append_mode && st.st_size > file->length)
1284                 return;
1285
1286         if (fnamecmp_type <= FNAMECMP_BASIS_DIR_HIGH)
1287                 ;
1288         else if (fnamecmp_type == FNAMECMP_FUZZY)
1289                 ;
1290         else if (unchanged_file(fnamecmp, file, &st)) {
1291                 if (partialptr) {
1292                         do_unlink(partialptr);
1293                         handle_partial_dir(partialptr, PDIR_DELETE);
1294                 }
1295                 if (itemizing) {
1296                         itemize(file, ndx, real_ret, &real_st,
1297                                 0, 0, NULL);
1298                 }
1299                 set_file_attrs(fname, file, &st, maybe_ATTRS_REPORT);
1300                 if (preserve_hard_links && file->link_u.links)
1301                         hard_link_cluster(file, ndx, itemizing, code);
1302                 if (remove_source_files != 1)
1303                         return;
1304           return_with_success:
1305                 if (!dry_run) {
1306                         char numbuf[4];
1307                         SIVAL(numbuf, 0, ndx);
1308                         send_msg(MSG_SUCCESS, numbuf, 4);
1309                 }
1310                 return;
1311         }
1312
1313   prepare_to_open:
1314         if (partialptr) {
1315                 st = partial_st;
1316                 fnamecmp = partialptr;
1317                 fnamecmp_type = FNAMECMP_PARTIAL_DIR;
1318                 statret = 0;
1319         }
1320
1321         if (!do_xfers || read_batch || whole_file)
1322                 goto notify_others;
1323
1324         if (fuzzy_dirlist) {
1325                 int j = flist_find(fuzzy_dirlist, file);
1326                 if (j >= 0) /* don't use changing file as future fuzzy basis */
1327                         fuzzy_dirlist->files[j]->flags |= FLAG_NO_FUZZY;
1328         }
1329
1330         /* open the file */
1331         fd = do_open(fnamecmp, O_RDONLY, 0);
1332
1333         if (fd == -1) {
1334                 rsyserr(FERROR, errno, "failed to open %s, continuing",
1335                         full_fname(fnamecmp));
1336           pretend_missing:
1337                 /* pretend the file didn't exist */
1338                 if (preserve_hard_links && file->link_u.links
1339                     && hard_link_check(file, ndx, fname, statret, &st,
1340                                        itemizing, code, HL_SKIP))
1341                         return;
1342                 statret = real_ret = -1;
1343                 goto notify_others;
1344         }
1345
1346         if (inplace && make_backups && fnamecmp_type == FNAMECMP_FNAME) {
1347                 if (!(backupptr = get_backup_name(fname))) {
1348                         close(fd);
1349                         return;
1350                 }
1351                 if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) {
1352                         close(fd);
1353                         goto pretend_missing;
1354                 }
1355                 if (robust_unlink(backupptr) && errno != ENOENT) {
1356                         rsyserr(FERROR, errno, "unlink %s",
1357                                 full_fname(backupptr));
1358                         free(back_file);
1359                         close(fd);
1360                         return;
1361                 }
1362                 if ((f_copy = do_open(backupptr,
1363                     O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) {
1364                         rsyserr(FERROR, errno, "open %s",
1365                                 full_fname(backupptr));
1366                         free(back_file);
1367                         close(fd);
1368                         return;
1369                 }
1370                 fnamecmp_type = FNAMECMP_BACKUP;
1371         }
1372
1373         if (verbose > 3) {
1374                 rprintf(FINFO, "gen mapped %s of size %.0f\n",
1375                         fnamecmp, (double)st.st_size);
1376         }
1377
1378         if (verbose > 2)
1379                 rprintf(FINFO, "generating and sending sums for %d\n", ndx);
1380
1381   notify_others:
1382         if (remove_source_files && !delay_updates && !phase)
1383                 increment_active_files(ndx, itemizing, code);
1384         write_int(f_out, ndx);
1385         if (itemizing) {
1386                 int iflags = ITEM_TRANSFER;
1387                 if (always_checksum)
1388                         iflags |= ITEM_REPORT_CHECKSUM;
1389                 if (fnamecmp_type != FNAMECMP_FNAME)
1390                         iflags |= ITEM_BASIS_TYPE_FOLLOWS;
1391                 if (fnamecmp_type == FNAMECMP_FUZZY)
1392                         iflags |= ITEM_XNAME_FOLLOWS;
1393                 itemize(file, -1, real_ret, &real_st, iflags, fnamecmp_type,
1394                         fuzzy_file ? fuzzy_file->basename : NULL);
1395         }
1396
1397         if (!do_xfers) {
1398                 if (preserve_hard_links && file->link_u.links)
1399                         hard_link_cluster(file, ndx, itemizing, code);
1400                 return;
1401         }
1402         if (read_batch)
1403                 return;
1404
1405         if (statret != 0 || whole_file) {
1406                 write_sum_head(f_out, NULL);
1407                 return;
1408         }
1409
1410         generate_and_send_sums(fd, st.st_size, f_out, f_copy);
1411
1412         if (f_copy >= 0) {
1413                 close(f_copy);
1414                 set_file_attrs(backupptr, back_file, NULL, 0);
1415                 if (verbose > 1) {
1416                         rprintf(FINFO, "backed up %s to %s\n",
1417                                 fname, backupptr);
1418                 }
1419                 free(back_file);
1420         }
1421
1422         close(fd);
1423 }
1424
1425 void generate_files(int f_out, struct file_list *flist, char *local_name)
1426 {
1427         int i;
1428         char fbuf[MAXPATHLEN];
1429         int itemizing, maybe_ATTRS_REPORT;
1430         enum logcode code;
1431         int lull_mod = allowed_lull * 5;
1432         int need_retouch_dir_times = preserve_times && !omit_dir_times;
1433         int need_retouch_dir_perms = 0;
1434         int save_ignore_existing = ignore_existing;
1435         int save_ignore_non_existing = ignore_non_existing;
1436         int save_do_progress = do_progress;
1437         int save_make_backups = make_backups;
1438         int dir_tweaking = !(list_only || local_name || dry_run);
1439
1440         if (protocol_version >= 29) {
1441                 itemizing = 1;
1442                 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
1443                 code = logfile_format_has_i ? FNONE : FLOG;
1444         } else if (am_daemon) {
1445                 itemizing = logfile_format_has_i && do_xfers;
1446                 maybe_ATTRS_REPORT = ATTRS_REPORT;
1447                 code = itemizing || !do_xfers ? FCLIENT : FINFO;
1448         } else if (!am_server) {
1449                 itemizing = stdout_format_has_i;
1450                 maybe_ATTRS_REPORT = stdout_format_has_i ? 0 : ATTRS_REPORT;
1451                 code = itemizing ? FNONE : FINFO;
1452         } else {
1453                 itemizing = 0;
1454                 maybe_ATTRS_REPORT = ATTRS_REPORT;
1455                 code = FINFO;
1456         }
1457
1458         if (verbose > 2) {
1459                 rprintf(FINFO, "generator starting pid=%ld count=%d\n",
1460                         (long)getpid(), flist->count);
1461         }
1462
1463         if (delete_before && !local_name && flist->count > 0)
1464                 do_delete_pass(flist);
1465         do_progress = 0;
1466
1467         if (append_mode || whole_file < 0)
1468                 whole_file = 0;
1469         if (verbose >= 2) {
1470                 rprintf(FINFO, "delta-transmission %s\n",
1471                         whole_file
1472                         ? "disabled for local transfer or --whole-file"
1473                         : "enabled");
1474         }
1475
1476         /* Since we often fill up the outgoing socket and then just sit around
1477          * waiting for the other 2 processes to do their thing, we don't want
1478          * to exit on a timeout.  If the data stops flowing, the receiver will
1479          * notice that and let us know via the redo pipe (or its closing). */
1480         ignore_timeout = 1;
1481
1482         for (i = 0; i < flist->count; i++) {
1483                 struct file_struct *file = flist->files[i];
1484
1485                 if (!file->basename)
1486                         continue;
1487
1488                 if (local_name)
1489                         strlcpy(fbuf, local_name, sizeof fbuf);
1490                 else
1491                         f_name(file, fbuf);
1492                 recv_generator(fbuf, file, i, itemizing, maybe_ATTRS_REPORT,
1493                                code, f_out);
1494
1495                 /* We need to ensure that any dirs we create have writeable
1496                  * permissions during the time we are putting files within
1497                  * them.  This is then fixed after the transfer is done. */
1498 #ifdef HAVE_CHMOD
1499                 if (!am_root && S_ISDIR(file->mode) && !(file->mode & S_IWUSR)
1500                  && dir_tweaking) {
1501                         mode_t mode = file->mode | S_IWUSR; /* user write */
1502                         char *fname = local_name ? local_name : fbuf;
1503                         if (do_chmod(fname, mode) < 0) {
1504                                 rsyserr(FERROR, errno,
1505                                         "failed to modify permissions on %s",
1506                                         full_fname(fname));
1507                         }
1508                         need_retouch_dir_perms = 1;
1509                 }
1510 #endif
1511
1512                 if (preserve_hard_links)
1513                         check_for_finished_hlinks(itemizing, code);
1514
1515                 if (allowed_lull && !(i % lull_mod))
1516                         maybe_send_keepalive();
1517                 else if (!(i % 200))
1518                         maybe_flush_socket();
1519         }
1520         recv_generator(NULL, NULL, 0, 0, 0, code, -1);
1521         if (delete_during)
1522                 delete_in_dir(NULL, NULL, NULL, NULL);
1523
1524         phase++;
1525         csum_length = SUM_LENGTH;
1526         max_size = min_size = ignore_existing = ignore_non_existing = 0;
1527         update_only = always_checksum = size_only = 0;
1528         ignore_times = 1;
1529         if (append_mode)  /* resend w/o append mode */
1530                 append_mode = -1; /* ... but only longer files */
1531         make_backups = 0; /* avoid a duplicate backup for inplace processing */
1532
1533         if (verbose > 2)
1534                 rprintf(FINFO,"generate_files phase=%d\n",phase);
1535
1536         write_int(f_out, -1);
1537
1538         /* files can cycle through the system more than once
1539          * to catch initial checksum errors */
1540         while ((i = get_redo_num(itemizing, code)) != -1) {
1541                 struct file_struct *file = flist->files[i];
1542                 if (local_name)
1543                         strlcpy(fbuf, local_name, sizeof fbuf);
1544                 else
1545                         f_name(file, fbuf);
1546                 recv_generator(fbuf, file, i, itemizing, maybe_ATTRS_REPORT,
1547                                code, f_out);
1548         }
1549
1550         phase++;
1551         ignore_non_existing = save_ignore_non_existing;
1552         ignore_existing = save_ignore_existing;
1553         make_backups = save_make_backups;
1554
1555         if (verbose > 2)
1556                 rprintf(FINFO,"generate_files phase=%d\n",phase);
1557
1558         write_int(f_out, -1);
1559         /* Reduce round-trip lag-time for a useless delay-updates phase. */
1560         if (protocol_version >= 29 && !delay_updates)
1561                 write_int(f_out, -1);
1562
1563         /* Read MSG_DONE for the redo phase (and any prior messages). */
1564         get_redo_num(itemizing, code);
1565
1566         if (protocol_version >= 29) {
1567                 phase++;
1568                 if (verbose > 2)
1569                         rprintf(FINFO, "generate_files phase=%d\n", phase);
1570                 if (delay_updates)
1571                         write_int(f_out, -1);
1572                 /* Read MSG_DONE for delay-updates phase & prior messages. */
1573                 get_redo_num(itemizing, code);
1574         }
1575
1576         do_progress = save_do_progress;
1577         if (delete_after && !local_name && flist->count > 0)
1578                 do_delete_pass(flist);
1579
1580         if ((need_retouch_dir_perms || need_retouch_dir_times) && dir_tweaking) {
1581                 int j = 0;
1582                 /* Now we need to fix any directory permissions that were
1583                  * modified during the transfer and/or re-set any tweaked
1584                  * modified-time values. */
1585                 for (i = 0; i < flist->count; i++) {
1586                         struct file_struct *file = flist->files[i];
1587
1588                         if (!file->basename || !S_ISDIR(file->mode))
1589                                 continue;
1590                         if (!need_retouch_dir_times && file->mode & S_IWUSR)
1591                                 continue;
1592                         if (file->flags & FLAG_MISSING) {
1593                                 int missing = file->dir.depth;
1594                                 while (++i < flist->count) {
1595                                         file = flist->files[i];
1596                                         if (file->dir.depth <= missing)
1597                                                 break;
1598                                 }
1599                                 i--;
1600                                 continue;
1601                         }
1602                         recv_generator(f_name(file, NULL), file, i, itemizing,
1603                                        maybe_ATTRS_REPORT, code, -1);
1604                         if (allowed_lull && !(++j % lull_mod))
1605                                 maybe_send_keepalive();
1606                         else if (!(j % 200))
1607                                 maybe_flush_socket();
1608                 }
1609         }
1610         recv_generator(NULL, NULL, 0, 0, 0, code, -1);
1611
1612         if (max_delete > 0 && deletion_count > max_delete) {
1613                 rprintf(FINFO,
1614                         "Deletions stopped due to --max-delete limit (%d skipped)\n",
1615                         deletion_count - max_delete);
1616                 io_error |= IOERR_DEL_LIMIT;
1617         }
1618
1619         if (verbose > 2)
1620                 rprintf(FINFO,"generate_files finished\n");
1621 }