if we get EWOULDBLOCK on a write then reduce the amount of data we are
[rsync/rsync.git] / rsync.c
1 /* 
2    Copyright (C) Andrew Tridgell 1996
3    Copyright (C) Paul Mackerras 1996
4    
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2 of the License, or
8    (at your option) any later version.
9    
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14    
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20 #include "rsync.h"
21
22 extern int csum_length;
23
24 extern int verbose;
25 extern int am_server;
26 extern int always_checksum;
27 extern time_t starttime;
28
29 extern int remote_version;
30
31 extern char *backup_suffix;
32 extern char *tmpdir;
33
34 extern int whole_file;
35 extern int block_size;
36 extern int update_only;
37 extern int make_backups;
38 extern int preserve_links;
39 extern int preserve_hard_links;
40 extern int preserve_perms;
41 extern int preserve_devices;
42 extern int preserve_uid;
43 extern int preserve_gid;
44 extern int preserve_times;
45 extern int dry_run;
46 extern int ignore_times;
47 extern int recurse;
48 extern int delete_mode;
49 extern int cvs_exclude;
50 extern int am_root;
51 extern int relative_paths;
52 extern int io_timeout;
53 extern int io_error;
54 extern struct stats stats;
55
56 /*
57   free a sums struct
58   */
59 static void free_sums(struct sum_struct *s)
60 {
61   if (s->sums) free(s->sums);
62   free(s);
63 }
64
65
66 /*
67  * delete a file or directory. If force_delet is set then delete 
68  * recursively 
69  */
70 static int delete_file(char *fname)
71 {
72         DIR *d;
73         struct dirent *di;
74         char buf[MAXPATHLEN];
75         extern int force_delete;
76         STRUCT_STAT st;
77         int ret;
78         extern int recurse;
79
80         if (do_unlink(fname) == 0 || errno == ENOENT) return 0;
81
82 #if SUPPORT_LINKS
83         ret = do_lstat(fname, &st);
84 #else
85         ret = do_stat(fname, &st);
86 #endif
87         if (ret) {
88                 rprintf(FERROR,"stat(%s) : %s\n", fname, strerror(errno));
89                 return -1;
90         }
91
92         if (!S_ISDIR(st.st_mode)) {
93                 rprintf(FERROR,"unlink(%s) : %s\n", fname, strerror(errno));
94                 return -1;
95         }
96
97         if (do_rmdir(fname) == 0 || errno == ENOENT) return 0;
98         if (!force_delete || !recurse || 
99             (errno != ENOTEMPTY && errno != EEXIST)) {
100                 rprintf(FERROR,"rmdir(%s) : %s\n", fname, strerror(errno));
101                 return -1;
102         }
103
104         /* now we do a recsursive delete on the directory ... */
105         d = opendir(fname);
106         if (!d) {
107                 rprintf(FERROR,"opendir(%s): %s\n",
108                         fname,strerror(errno));
109                 return -1;
110         }
111
112         for (di=readdir(d); di; di=readdir(d)) {
113                 char *dname = d_name(di);
114                 if (strcmp(dname,".")==0 ||
115                     strcmp(dname,"..")==0)
116                         continue;
117                 slprintf(buf, sizeof(buf)-1, "%s/%s", fname, dname);
118                 if (verbose > 0)
119                         rprintf(FINFO,"deleting %s\n", buf);
120                 if (delete_file(buf) != 0) {
121                         closedir(d);
122                         return -1;
123                 }
124         }       
125
126         closedir(d);
127         
128         if (do_rmdir(fname) != 0) {
129                 rprintf(FERROR,"rmdir(%s) : %s\n", fname, strerror(errno));
130                 return -1;
131         }
132
133         return 0;
134 }
135
136 /*
137   send a sums struct down a fd
138   */
139 static void send_sums(struct sum_struct *s,int f_out)
140 {
141   int i;
142
143   /* tell the other guy how many we are going to be doing and how many
144      bytes there are in the last chunk */
145   write_int(f_out,s?s->count:0);
146   write_int(f_out,s?s->n:block_size);
147   write_int(f_out,s?s->remainder:0);
148   if (s)
149     for (i=0;i<s->count;i++) {
150       write_int(f_out,s->sums[i].sum1);
151       write_buf(f_out,s->sums[i].sum2,csum_length);
152     }
153 }
154
155
156 /*
157   generate a stream of signatures/checksums that describe a buffer
158
159   generate approximately one checksum every n bytes
160   */
161 static struct sum_struct *generate_sums(struct map_struct *buf,OFF_T len,int n)
162 {
163   int i;
164   struct sum_struct *s;
165   int count;
166   int block_len = n;
167   int remainder = (len%block_len);
168   OFF_T offset = 0;
169
170   count = (len+(block_len-1))/block_len;
171
172   s = (struct sum_struct *)malloc(sizeof(*s));
173   if (!s) out_of_memory("generate_sums");
174
175   s->count = count;
176   s->remainder = remainder;
177   s->n = n;
178   s->flength = len;
179
180   if (count==0) {
181     s->sums = NULL;
182     return s;
183   }
184
185   if (verbose > 3)
186     rprintf(FINFO,"count=%d rem=%d n=%d flength=%d\n",
187             s->count,s->remainder,s->n,(int)s->flength);
188
189   s->sums = (struct sum_buf *)malloc(sizeof(s->sums[0])*s->count);
190   if (!s->sums) out_of_memory("generate_sums");
191   
192   for (i=0;i<count;i++) {
193     int n1 = MIN(len,n);
194     char *map = map_ptr(buf,offset,n1);
195
196     s->sums[i].sum1 = get_checksum1(map,n1);
197     get_checksum2(map,n1,s->sums[i].sum2);
198
199     s->sums[i].offset = offset;
200     s->sums[i].len = n1;
201     s->sums[i].i = i;
202
203     if (verbose > 3)
204       rprintf(FINFO,"chunk[%d] offset=%d len=%d sum1=%08x\n",
205               i,(int)s->sums[i].offset,s->sums[i].len,s->sums[i].sum1);
206
207     len -= n1;
208     offset += n1;
209   }
210
211   return s;
212 }
213
214
215 /*
216   receive the checksums for a buffer
217   */
218 static struct sum_struct *receive_sums(int f)
219 {
220   struct sum_struct *s;
221   int i;
222   OFF_T offset = 0;
223
224   s = (struct sum_struct *)malloc(sizeof(*s));
225   if (!s) out_of_memory("receive_sums");
226
227   s->count = read_int(f);
228   s->n = read_int(f);
229   s->remainder = read_int(f);  
230   s->sums = NULL;
231
232   if (verbose > 3)
233     rprintf(FINFO,"count=%d n=%d rem=%d\n",
234             s->count,s->n,s->remainder);
235
236   if (s->count == 0) 
237     return(s);
238
239   s->sums = (struct sum_buf *)malloc(sizeof(s->sums[0])*s->count);
240   if (!s->sums) out_of_memory("receive_sums");
241
242   for (i=0;i<s->count;i++) {
243     s->sums[i].sum1 = read_int(f);
244     read_buf(f,s->sums[i].sum2,csum_length);
245
246     s->sums[i].offset = offset;
247     s->sums[i].i = i;
248
249     if (i == s->count-1 && s->remainder != 0) {
250       s->sums[i].len = s->remainder;
251     } else {
252       s->sums[i].len = s->n;
253     }
254     offset += s->sums[i].len;
255
256     if (verbose > 3)
257       rprintf(FINFO,"chunk[%d] len=%d offset=%d sum1=%08x\n",
258               i,s->sums[i].len,(int)s->sums[i].offset,s->sums[i].sum1);
259   }
260
261   s->flength = offset;
262
263   return s;
264 }
265
266
267 static int set_perms(char *fname,struct file_struct *file,STRUCT_STAT *st,
268                      int report)
269 {
270         int updated = 0;
271         STRUCT_STAT st2;
272         extern int am_daemon;
273
274         if (dry_run) return 0;
275
276         if (!st) {
277                 if (link_stat(fname,&st2) != 0) {
278                         rprintf(FERROR,"stat %s : %s\n",fname,strerror(errno));
279                         return 0;
280                 }
281                 st = &st2;
282         }
283
284         if (preserve_times && !S_ISLNK(st->st_mode) &&
285             st->st_mtime != file->modtime) {
286                 updated = 1;
287                 if (set_modtime(fname,file->modtime) != 0) {
288                         rprintf(FERROR,"failed to set times on %s : %s\n",
289                                 fname,strerror(errno));
290                         return 0;
291                 }
292         }
293
294         if ((am_root || !am_daemon) &&
295             ((am_root && preserve_uid && st->st_uid != file->uid) || 
296              (preserve_gid && st->st_gid != file->gid))) {
297                 if (do_lchown(fname,
298                               (am_root&&preserve_uid)?file->uid:-1,
299                               preserve_gid?file->gid:-1) != 0) {
300                         if (preserve_uid && st->st_uid != file->uid)
301                                 updated = 1;
302                         if (verbose>1 || preserve_uid) {
303                                 rprintf(FERROR,"chown %s : %s\n",
304                                         fname,strerror(errno));
305                                 return 0;
306                         }
307                 } else {
308                         updated = 1;
309                 }
310         }
311
312 #ifdef HAVE_CHMOD
313         if (preserve_perms && !S_ISLNK(st->st_mode) &&
314             (st->st_mode != file->mode || 
315              (updated && (file->mode & ~ACCESSPERMS)))) {
316                 updated = 1;
317                 if (do_chmod(fname,file->mode) != 0) {
318                         rprintf(FERROR,"failed to set permissions on %s : %s\n",
319                                 fname,strerror(errno));
320                         return 0;
321                 }
322         }
323 #endif
324     
325         if (verbose > 1 && report) {
326                 if (updated)
327                         rprintf(FINFO,"%s\n",fname);
328                 else
329                         rprintf(FINFO,"%s is uptodate\n",fname);
330         }
331         return updated;
332 }
333
334
335 /* choose whether to skip a particular file */
336 static int skip_file(char *fname,
337                      struct file_struct *file, STRUCT_STAT *st)
338 {
339         if (st->st_size != file->length) {
340                 return 0;
341         }
342         
343         /* if always checksum is set then we use the checksum instead 
344            of the file time to determine whether to sync */
345         if (always_checksum && S_ISREG(st->st_mode)) {
346                 char sum[MD4_SUM_LENGTH];
347                 file_checksum(fname,sum,st->st_size);
348                 return (memcmp(sum,file->sum,csum_length) == 0);
349         }
350
351         if (ignore_times) {
352                 return 0;
353         }
354
355         return (st->st_mtime == file->modtime);
356 }
357
358
359 /* use a larger block size for really big files */
360 int adapt_block_size(struct file_struct *file, int bsize)
361 {
362         int ret;
363
364         if (bsize != BLOCK_SIZE) return bsize;
365
366         ret = file->length / (10000); /* rough heuristic */
367         ret = ret & ~15; /* multiple of 16 */
368         if (ret < bsize) ret = bsize;
369         if (ret > CHUNK_SIZE/2) ret = CHUNK_SIZE/2;
370         return ret;
371 }
372
373 void recv_generator(char *fname,struct file_list *flist,int i,int f_out)
374 {  
375   int fd;
376   STRUCT_STAT st;
377   struct map_struct *buf;
378   struct sum_struct *s;
379   int statret;
380   struct file_struct *file = flist->files[i];
381
382   if (verbose > 2)
383     rprintf(FINFO,"recv_generator(%s,%d)\n",fname,i);
384
385   statret = link_stat(fname,&st);
386
387   if (S_ISDIR(file->mode)) {
388     if (dry_run) return;
389     if (statret == 0 && !S_ISDIR(st.st_mode)) {
390       if (do_unlink(fname) != 0) {
391         rprintf(FERROR,"unlink %s : %s\n",fname,strerror(errno));
392         return;
393       }
394       statret = -1;
395     }
396     if (statret != 0 && do_mkdir(fname,file->mode) != 0 && errno != EEXIST) {
397             if (!(relative_paths && errno==ENOENT && 
398                   create_directory_path(fname)==0 && 
399                   do_mkdir(fname,file->mode)==0)) {
400                     rprintf(FERROR,"mkdir %s : %s (2)\n",
401                             fname,strerror(errno));
402             }
403     }
404     if (set_perms(fname,file,NULL,0) && verbose) 
405       rprintf(FINFO,"%s/\n",fname);
406     return;
407   }
408
409   if (preserve_links && S_ISLNK(file->mode)) {
410 #if SUPPORT_LINKS
411     char lnk[MAXPATHLEN];
412     int l;
413     if (statret == 0) {
414       l = readlink(fname,lnk,MAXPATHLEN-1);
415       if (l > 0) {
416         lnk[l] = 0;
417         if (strcmp(lnk,file->link) == 0) {
418           set_perms(fname,file,&st,1);
419           return;
420         }
421       }
422     }
423     delete_file(fname);
424     if (do_symlink(file->link,fname) != 0) {
425       rprintf(FERROR,"link %s -> %s : %s\n",
426               fname,file->link,strerror(errno));
427     } else {
428       set_perms(fname,file,NULL,0);
429       if (verbose) 
430         rprintf(FINFO,"%s -> %s\n",
431                 fname,file->link);
432     }
433 #endif
434     return;
435   }
436
437 #ifdef HAVE_MKNOD
438   if (am_root && preserve_devices && IS_DEVICE(file->mode)) {
439     if (statret != 0 || 
440         st.st_mode != file->mode ||
441         st.st_rdev != file->rdev) {     
442       delete_file(fname);
443       if (verbose > 2)
444         rprintf(FINFO,"mknod(%s,0%o,0x%x)\n",
445                 fname,(int)file->mode,(int)file->rdev);
446       if (do_mknod(fname,file->mode,file->rdev) != 0) {
447         rprintf(FERROR,"mknod %s : %s\n",fname,strerror(errno));
448       } else {
449         set_perms(fname,file,NULL,0);
450         if (verbose)
451           rprintf(FINFO,"%s\n",fname);
452       }
453     } else {
454       set_perms(fname,file,&st,1);
455     }
456     return;
457   }
458 #endif
459
460   if (preserve_hard_links && check_hard_link(file)) {
461     if (verbose > 1)
462       rprintf(FINFO,"%s is a hard link\n",f_name(file));
463     return;
464   }
465
466   if (!S_ISREG(file->mode)) {
467     rprintf(FINFO,"skipping non-regular file %s\n",fname);
468     return;
469   }
470
471   if (statret == -1) {
472     if (errno == ENOENT) {
473       write_int(f_out,i);
474       if (!dry_run) send_sums(NULL,f_out);
475     } else {
476       if (verbose > 1)
477         rprintf(FERROR,"recv_generator failed to open %s\n",fname);
478     }
479     return;
480   }
481
482   if (!S_ISREG(st.st_mode)) {
483     if (delete_file(fname) != 0) {
484       return;
485     }
486
487     /* now pretend the file didn't exist */
488     write_int(f_out,i);
489     if (!dry_run) send_sums(NULL,f_out);    
490     return;
491   }
492
493   if (update_only && st.st_mtime > file->modtime) {
494     if (verbose > 1)
495       rprintf(FINFO,"%s is newer\n",fname);
496     return;
497   }
498
499   if (skip_file(fname, file, &st)) {
500     set_perms(fname,file,&st,1);
501     return;
502   }
503
504   if (dry_run) {
505     write_int(f_out,i);
506     return;
507   }
508
509   if (whole_file) {
510     write_int(f_out,i);
511     send_sums(NULL,f_out);    
512     return;
513   }
514
515   /* open the file */  
516   fd = open(fname,O_RDONLY);
517
518   if (fd == -1) {
519     rprintf(FERROR,"failed to open %s : %s\n",fname,strerror(errno));
520     rprintf(FERROR,"skipping %s\n",fname);
521     return;
522   }
523
524   if (st.st_size > 0) {
525     buf = map_file(fd,st.st_size);
526   } else {
527     buf = NULL;
528   }
529
530   if (verbose > 3)
531     rprintf(FINFO,"gen mapped %s of size %d\n",fname,(int)st.st_size);
532
533   s = generate_sums(buf,st.st_size,adapt_block_size(file, block_size));
534
535   if (verbose > 2)
536     rprintf(FINFO,"sending sums for %d\n",i);
537
538   write_int(f_out,i);
539   send_sums(s,f_out);
540
541   close(fd);
542   if (buf) unmap_file(buf);
543
544   free_sums(s);
545 }
546
547
548
549 static int receive_data(int f_in,struct map_struct *buf,int fd,char *fname)
550 {
551   int i,n,remainder,len,count;
552   OFF_T offset = 0;
553   OFF_T offset2;
554   char *data;
555   static char file_sum1[MD4_SUM_LENGTH];
556   static char file_sum2[MD4_SUM_LENGTH];
557   char *map=NULL;
558
559   count = read_int(f_in);
560   n = read_int(f_in);
561   remainder = read_int(f_in);
562
563   sum_init();
564
565   for (i=recv_token(f_in,&data); i != 0; i=recv_token(f_in,&data)) {
566     if (i > 0) {
567       if (verbose > 3)
568         rprintf(FINFO,"data recv %d at %d\n",i,(int)offset);
569
570       stats.literal_data += i;
571       sum_update(data,i);
572
573       if (fd != -1 && write_file(fd,data,i) != i) {
574         rprintf(FERROR,"write failed on %s : %s\n",fname,strerror(errno));
575         exit_cleanup(1);
576       }
577       offset += i;
578     } else {
579       i = -(i+1);
580       offset2 = i*n;
581       len = n;
582       if (i == count-1 && remainder != 0)
583         len = remainder;
584
585       stats.matched_data += len;
586
587       if (verbose > 3)
588         rprintf(FINFO,"chunk[%d] of size %d at %d offset=%d\n",
589                 i,len,(int)offset2,(int)offset);
590
591       map = map_ptr(buf,offset2,len);
592
593       see_token(map, len);
594       sum_update(map,len);
595
596       if (fd != -1 && write_file(fd,map,len) != len) {
597         rprintf(FERROR,"write failed on %s : %s\n",fname,strerror(errno));
598         exit_cleanup(1);
599       }
600       offset += len;
601     }
602   }
603
604   if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
605     rprintf(FERROR,"write failed on %s : %s\n",fname,strerror(errno));
606     exit_cleanup(1);
607   }
608
609   sum_end(file_sum1);
610
611   if (remote_version >= 14) {
612     read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
613     if (verbose > 2)
614       rprintf(FINFO,"got file_sum\n");
615     if (fd != -1 && memcmp(file_sum1,file_sum2,MD4_SUM_LENGTH) != 0)
616       return 0;
617   }
618   return 1;
619 }
620
621
622 static void delete_one(struct file_struct *f)
623 {
624   if (!S_ISDIR(f->mode)) {
625     if (do_unlink(f_name(f)) != 0) {
626       rprintf(FERROR,"unlink %s : %s\n",f_name(f),strerror(errno));
627     } else if (verbose) {
628       rprintf(FINFO,"deleting %s\n",f_name(f));
629     }
630   } else {    
631     if (do_rmdir(f_name(f)) != 0) {
632       if (errno != ENOTEMPTY && errno != EEXIST)
633         rprintf(FERROR,"rmdir %s : %s\n",f_name(f),strerror(errno));
634     } else if (verbose) {
635       rprintf(FINFO,"deleting directory %s\n",f_name(f));      
636     }
637   }
638 }
639
640
641
642 static struct delete_list {
643         dev_t dev;
644         ino_t inode;
645 } *delete_list;
646 static int dlist_len, dlist_alloc_len;
647
648 static void add_delete_entry(struct file_struct *file)
649 {
650         if (dlist_len == dlist_alloc_len) {
651                 dlist_alloc_len += 1024;
652                 delete_list = (struct delete_list *)Realloc(delete_list, sizeof(delete_list[0])*dlist_alloc_len);
653                 if (!delete_list) out_of_memory("add_delete_entry");
654         }
655
656         delete_list[dlist_len].dev = file->dev;
657         delete_list[dlist_len].inode = file->inode;
658         dlist_len++;
659
660         if (verbose > 3)
661                 rprintf(FINFO,"added %s to delete list\n", f_name(file));
662 }
663
664 /* yuck! This function wouldn't have been necessary if I had the sorting
665    algorithm right. Unfortunately fixing the sorting algorithm would introduce
666    a backward incompatibility as file list indexes are sent over the link.
667 */
668 static int delete_already_done(struct file_list *flist,int j)
669 {
670         int i;
671         STRUCT_STAT st;
672
673         if (link_stat(f_name(flist->files[j]), &st)) return 1;
674
675         for (i=0;i<dlist_len;i++) {
676                 if (st.st_ino == delete_list[i].inode &&
677                     st.st_dev == delete_list[i].dev)
678                         return 1;
679         }
680
681         return 0;
682 }
683
684
685 /* this deletes any files on the receiving side that are not present
686    on the sending side. For version 1.6.4 I have changed the behaviour
687    to match more closely what most people seem to expect of this option */
688 static void delete_files(struct file_list *flist)
689 {
690         struct file_list *local_file_list;
691         int i, j;
692         char *name;
693
694         if (cvs_exclude)
695                 add_cvs_excludes();
696
697         if (io_error) {
698                 rprintf(FINFO,"IO error encountered - skipping file deletion\n");
699                 return;
700         }
701
702         for (j=0;j<flist->count;j++) {
703                 if (!S_ISDIR(flist->files[j]->mode) || 
704                     !(flist->files[j]->flags & FLAG_DELETE)) continue;
705
706                 if (remote_version < 19 &&
707                     delete_already_done(flist, j)) continue;
708
709                 name = strdup(f_name(flist->files[j]));
710
711                 if (!(local_file_list = send_file_list(-1,1,&name))) {
712                         free(name);
713                         continue;
714                 }
715
716                 if (verbose > 1)
717                         rprintf(FINFO,"deleting in %s\n", name);
718
719                 for (i=local_file_list->count-1;i>=0;i--) {
720                         if (!local_file_list->files[i]->basename) continue;
721                         if (remote_version < 19 &&
722                             S_ISDIR(local_file_list->files[i]->mode))
723                                 add_delete_entry(local_file_list->files[i]);
724                         if (-1 == flist_find(flist,local_file_list->files[i])) {
725                                 delete_one(local_file_list->files[i]);
726                         }    
727                 }
728                 flist_free(local_file_list);
729                 free(name);
730         }
731 }
732
733 static char *cleanup_fname;
734
735 void exit_cleanup(int code)
736 {
737         io_flush();
738         if (cleanup_fname)
739                 do_unlink(cleanup_fname);
740         signal(SIGUSR1, SIG_IGN);
741         if (code) {
742                 kill_all(SIGUSR1);
743         }
744         exit(code);
745 }
746
747 void sig_int(void)
748 {
749   exit_cleanup(1);
750 }
751
752
753
754
755 static int get_tmpname(char *fnametmp, char *fname)
756 {
757         char *f;
758
759         /* open tmp file */
760         if (tmpdir) {
761                 f = strrchr(fname,'/');
762                 if (f == NULL) 
763                         f = fname;
764                 else 
765                         f++;
766                 if (strlen(tmpdir)+strlen(f)+10 > MAXPATHLEN) {
767                         rprintf(FERROR,"filename too long\n");
768                         return 0;
769                 }
770                 slprintf(fnametmp,MAXPATHLEN-1, "%s/.%s.XXXXXX",tmpdir,f);
771                 return 1;
772         } 
773
774         f = strrchr(fname,'/');
775
776         if (strlen(fname)+9 > MAXPATHLEN) {
777                 rprintf(FERROR,"filename too long\n");
778                 return 0;
779         }
780
781         if (f) {
782                 *f = 0;
783                 slprintf(fnametmp,MAXPATHLEN-1,"%s/.%s.XXXXXX",
784                          fname,f+1);
785                 *f = '/';
786         } else {
787                 slprintf(fnametmp,MAXPATHLEN-1,".%s.XXXXXX",fname);
788         }
789
790         return 1;
791 }
792
793 int recv_files(int f_in,struct file_list *flist,char *local_name,int f_gen)
794 {  
795         int fd1,fd2;
796         STRUCT_STAT st;
797         char *fname;
798         char fnametmp[MAXPATHLEN];
799         struct map_struct *buf;
800         int i;
801         struct file_struct *file;
802         int phase=0;
803         int recv_ok;
804         
805         if (verbose > 2) {
806                 rprintf(FINFO,"recv_files(%d) starting\n",flist->count);
807         }
808
809         if (recurse && delete_mode && !local_name && flist->count>0) {
810                 delete_files(flist);
811         }
812
813         while (1) {      
814                 i = read_int(f_in);
815                 if (i == -1) {
816                         if (phase==0 && remote_version >= 13) {
817                                 phase++;
818                                 csum_length = SUM_LENGTH;
819                                 if (verbose > 2)
820                                         rprintf(FINFO,"recv_files phase=%d\n",phase);
821                                 write_int(f_gen,-1);
822                                 continue;
823                         }
824                         break;
825                 }
826
827                 if (i < 0 || i >= flist->count) {
828                         rprintf(FERROR,"Invalid file index %d in recv_files (count=%d)\n", 
829                                 i, flist->count);
830                         exit_cleanup(1);
831                 }
832
833                 file = flist->files[i];
834                 fname = f_name(file);
835
836                 stats.num_transferred_files++;
837                 stats.total_transferred_size += file->length;
838
839                 if (local_name)
840                         fname = local_name;
841
842                 if (dry_run) {
843                         if (!am_server && verbose)
844                                 printf("%s\n",fname);
845                         continue;
846                 }
847
848                 if (verbose > 2)
849                         rprintf(FINFO,"recv_files(%s)\n",fname);
850
851                 /* open the file */  
852                 fd1 = open(fname,O_RDONLY);
853
854                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
855                         rprintf(FERROR,"fstat %s : %s\n",fname,strerror(errno));
856                         receive_data(f_in,NULL,-1,NULL);
857                         close(fd1);
858                         continue;
859                 }
860
861                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
862                         rprintf(FERROR,"%s : not a regular file (recv_files)\n",fname);
863                         receive_data(f_in,NULL,-1,NULL);
864                         close(fd1);
865                         continue;
866                 }
867
868                 if (fd1 != -1 && st.st_size > 0) {
869                         buf = map_file(fd1,st.st_size);
870                         if (verbose > 2)
871                                 rprintf(FINFO,"recv mapped %s of size %d\n",fname,(int)st.st_size);
872                 } else {
873                         buf = NULL;
874                 }
875
876                 if (!get_tmpname(fnametmp,fname)) {
877                         if (buf) unmap_file(buf);
878                         close(fd1);
879                         continue;
880                 }
881
882                 if (NULL == do_mktemp(fnametmp)) {
883                         rprintf(FERROR,"mktemp %s failed\n",fnametmp);
884                         receive_data(f_in,buf,-1,NULL);
885                         if (buf) unmap_file(buf);
886                         close(fd1);
887                         continue;
888                 }
889
890                 /* we initially set the perms without the
891                    setuid/setgid bits to ensure that there is no race
892                    condition. They are then correctly updated after
893                    the lchown. Thanks to snabb@epipe.fi for pointing
894                    this out */
895                 fd2 = do_open(fnametmp,O_WRONLY|O_CREAT|O_EXCL,
896                               file->mode & ACCESSPERMS);
897
898                 if (fd2 == -1 && relative_paths && errno == ENOENT && 
899                     create_directory_path(fnametmp) == 0) {
900                         fd2 = do_open(fnametmp,O_WRONLY|O_CREAT|O_EXCL,
901                                       file->mode & ACCESSPERMS);
902                 }
903                 if (fd2 == -1) {
904                         rprintf(FERROR,"open %s : %s\n",fnametmp,strerror(errno));
905                         receive_data(f_in,buf,-1,NULL);
906                         if (buf) unmap_file(buf);
907                         close(fd1);
908                         continue;
909                 }
910       
911                 cleanup_fname = fnametmp;
912
913                 if (!am_server && verbose)
914                         printf("%s\n",fname);
915                 
916                 /* recv file data */
917                 recv_ok = receive_data(f_in,buf,fd2,fname);
918                 
919                 if (buf) unmap_file(buf);
920                 if (fd1 != -1) {
921                         close(fd1);
922                 }
923                 close(fd2);
924                 
925                 if (verbose > 2)
926                         rprintf(FINFO,"renaming %s to %s\n",fnametmp,fname);
927                 
928                 if (make_backups) {
929                         char fnamebak[MAXPATHLEN];
930                         if (strlen(fname) + strlen(backup_suffix) > (MAXPATHLEN-1)) {
931                                 rprintf(FERROR,"backup filename too long\n");
932                                 continue;
933                         }
934                         slprintf(fnamebak,sizeof(fnamebak)-1,"%s%s",fname,backup_suffix);
935                         if (do_rename(fname,fnamebak) != 0 && errno != ENOENT) {
936                                 rprintf(FERROR,"rename %s %s : %s\n",fname,fnamebak,strerror(errno));
937                                 continue;
938                         }
939                 }
940
941                 /* move tmp file over real file */
942                 if (do_rename(fnametmp,fname) != 0) {
943                         if (errno == EXDEV) {
944                                 /* rename failed on cross-filesystem link.  
945                                    Copy the file instead. */
946                                 if (copy_file(fnametmp,fname, file->mode)) {
947                                         rprintf(FERROR,"copy %s -> %s : %s\n",
948                                                 fnametmp,fname,strerror(errno));
949                                 } else {
950                                         set_perms(fname,file,NULL,0);
951                                 }
952                                 do_unlink(fnametmp);
953                         } else {
954                                 rprintf(FERROR,"rename %s -> %s : %s\n",
955                                         fnametmp,fname,strerror(errno));
956                                 do_unlink(fnametmp);
957                         }
958                 } else {
959                         set_perms(fname,file,NULL,0);
960                 }
961
962                 cleanup_fname = NULL;
963
964                 
965                 if (!recv_ok) {
966                         if (csum_length == SUM_LENGTH) {
967                                 rprintf(FERROR,"ERROR: file corruption in %s. File changed during transfer?\n",
968                                         fname);
969                         } else {
970                                 if (verbose > 1)
971                                         rprintf(FINFO,"redoing %s(%d)\n",fname,i);
972                                 write_int(f_gen,i);
973                         }
974                 }
975         }
976
977         if (preserve_hard_links)
978                 do_hard_links(flist);
979
980         /* now we need to fix any directory permissions that were 
981            modified during the transfer */
982         for (i = 0; i < flist->count; i++) {
983                 file = flist->files[i];
984                 if (!file->basename || !S_ISDIR(file->mode)) continue;
985                 recv_generator(f_name(file),flist,i,-1);
986         }
987
988         if (verbose > 2)
989                 rprintf(FINFO,"recv_files finished\n");
990         
991         return 0;
992 }
993
994
995
996 void send_files(struct file_list *flist,int f_out,int f_in)
997
998   int fd;
999   struct sum_struct *s;
1000   struct map_struct *buf;
1001   STRUCT_STAT st;
1002   char fname[MAXPATHLEN];  
1003   int i;
1004   struct file_struct *file;
1005   int phase = 0;
1006
1007   if (verbose > 2)
1008     rprintf(FINFO,"send_files starting\n");
1009
1010   setup_readbuffer(f_in);
1011
1012   while (1) {
1013           int offset=0;
1014
1015           i = read_int(f_in);
1016           if (i == -1) {
1017                   if (phase==0 && remote_version >= 13) {
1018                           phase++;
1019                           csum_length = SUM_LENGTH;
1020                           write_int(f_out,-1);
1021                           if (verbose > 2)
1022                                   rprintf(FINFO,"send_files phase=%d\n",phase);
1023                           continue;
1024                   }
1025                   break;
1026           }
1027
1028           if (i < 0 || i >= flist->count) {
1029                   rprintf(FERROR,"Invalid file index %d (count=%d)\n", 
1030                           i, flist->count);
1031                   exit_cleanup(1);
1032           }
1033
1034           file = flist->files[i];
1035
1036           stats.num_transferred_files++;
1037           stats.total_transferred_size += file->length;
1038
1039           fname[0] = 0;
1040           if (file->basedir) {
1041                   strlcpy(fname,file->basedir,MAXPATHLEN-1);
1042                   if (strlen(fname) == MAXPATHLEN-1) {
1043                           io_error = 1;
1044                           rprintf(FERROR, "send_files failed on long-named directory %s\n",
1045                                   fname);
1046                           return;
1047                   }
1048                   strlcat(fname,"/",MAXPATHLEN-1);
1049                   offset = strlen(file->basedir)+1;
1050           }
1051           strlcat(fname,f_name(file),MAXPATHLEN-strlen(fname));
1052           
1053           if (verbose > 2) 
1054                   rprintf(FINFO,"send_files(%d,%s)\n",i,fname);
1055           
1056           if (dry_run) {        
1057                   if (!am_server && verbose)
1058                           printf("%s\n",fname);
1059                   write_int(f_out,i);
1060                   continue;
1061           }
1062
1063           s = receive_sums(f_in);
1064           if (!s) {
1065                   io_error = 1;
1066                   rprintf(FERROR,"receive_sums failed\n");
1067                   return;
1068           }
1069           
1070           fd = open(fname,O_RDONLY);
1071           if (fd == -1) {
1072                   io_error = 1;
1073                   rprintf(FERROR,"send_files failed to open %s: %s\n",
1074                           fname,strerror(errno));
1075                   free_sums(s);
1076                   continue;
1077           }
1078           
1079           /* map the local file */
1080           if (do_fstat(fd,&st) != 0) {
1081                   io_error = 1;
1082                   rprintf(FERROR,"fstat failed : %s\n",strerror(errno));
1083                   free_sums(s);
1084                   close(fd);
1085                   return;
1086           }
1087           
1088           if (st.st_size > 0) {
1089                   buf = map_file(fd,st.st_size);
1090           } else {
1091                   buf = NULL;
1092           }
1093           
1094           if (verbose > 2)
1095                   rprintf(FINFO,"send_files mapped %s of size %d\n",
1096                           fname,(int)st.st_size);
1097           
1098           write_int(f_out,i);
1099           
1100           write_int(f_out,s->count);
1101           write_int(f_out,s->n);
1102           write_int(f_out,s->remainder);
1103           
1104           if (verbose > 2)
1105                   rprintf(FINFO,"calling match_sums %s\n",fname);
1106           
1107           if (!am_server && verbose)
1108                   printf("%s\n",fname+offset);
1109           
1110           match_sums(f_out,s,buf,st.st_size);
1111           
1112           if (buf) unmap_file(buf);
1113           close(fd);
1114           
1115           free_sums(s);
1116           
1117           if (verbose > 2)
1118                   rprintf(FINFO,"sender finished %s\n",fname);
1119   }
1120
1121   if (verbose > 2)
1122           rprintf(FINFO,"send files finished\n");
1123
1124   match_report();
1125
1126   write_int(f_out,-1);
1127 }
1128
1129
1130
1131 void generate_files(int f,struct file_list *flist,char *local_name,int f_recv)
1132 {
1133   int i;
1134   int phase=0;
1135
1136   if (verbose > 2)
1137     rprintf(FINFO,"generator starting pid=%d count=%d\n",
1138             (int)getpid(),flist->count);
1139
1140   for (i = 0; i < flist->count; i++) {
1141     struct file_struct *file = flist->files[i];
1142     mode_t saved_mode = file->mode;
1143     if (!file->basename) continue;
1144
1145     /* we need to ensure that any directories we create have writeable
1146        permissions initially so that we can create the files within
1147        them. This is then fixed after the files are transferred */
1148     if (!am_root && S_ISDIR(file->mode)) {
1149       file->mode |= S_IWUSR; /* user write */
1150     }
1151
1152     recv_generator(local_name?local_name:f_name(file),
1153                    flist,i,f);
1154
1155     file->mode = saved_mode;
1156   }
1157
1158   phase++;
1159   csum_length = SUM_LENGTH;
1160   ignore_times=1;
1161
1162   if (verbose > 2)
1163     rprintf(FINFO,"generate_files phase=%d\n",phase);
1164
1165   write_int(f,-1);
1166
1167   /* we expect to just sit around now, so don't exit on a timeout. If we
1168      really get a timeout then the other process should exit */
1169   io_timeout = 0;
1170
1171   if (remote_version >= 13) {
1172     /* in newer versions of the protocol the files can cycle through
1173        the system more than once to catch initial checksum errors */
1174     for (i=read_int(f_recv); i != -1; i=read_int(f_recv)) {
1175       struct file_struct *file = flist->files[i];
1176       recv_generator(local_name?local_name:f_name(file),
1177                      flist,i,f);    
1178     }
1179
1180     phase++;
1181     if (verbose > 2)
1182       rprintf(FINFO,"generate_files phase=%d\n",phase);
1183
1184     write_int(f,-1);
1185   }
1186 }
1187
1188