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