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