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