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