added --backup-dir option from Bob Edwards
[rsync/rsync.git] / receiver.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 verbose;
23 extern int recurse;
24 extern int delete_mode;
25 extern int remote_version;
26 extern int csum_length;
27 extern struct stats stats;
28 extern int dry_run;
29 extern int am_server;
30 extern int relative_paths;
31 extern int preserve_hard_links;
32 extern int cvs_exclude;
33 extern int io_error;
34 extern char *tmpdir;
35 extern char *compare_dest;
36 extern int make_backups;
37 extern char *backup_suffix;
38
39 static struct delete_list {
40         dev_t dev;
41         INO_T inode;
42 } *delete_list;
43 static int dlist_len, dlist_alloc_len;
44
45 /* yuck! This function wouldn't have been necessary if I had the sorting
46    algorithm right. Unfortunately fixing the sorting algorithm would introduce
47    a backward incompatibility as file list indexes are sent over the link.
48 */
49 static int delete_already_done(struct file_list *flist,int j)
50 {
51         int i;
52         STRUCT_STAT st;
53
54         if (link_stat(f_name(flist->files[j]), &st)) return 1;
55
56         for (i=0;i<dlist_len;i++) {
57                 if (st.st_ino == delete_list[i].inode &&
58                     st.st_dev == delete_list[i].dev)
59                         return 1;
60         }
61
62         return 0;
63 }
64
65 static void add_delete_entry(struct file_struct *file)
66 {
67         if (dlist_len == dlist_alloc_len) {
68                 dlist_alloc_len += 1024;
69                 delete_list = (struct delete_list *)Realloc(delete_list, sizeof(delete_list[0])*dlist_alloc_len);
70                 if (!delete_list) out_of_memory("add_delete_entry");
71         }
72
73         delete_list[dlist_len].dev = file->dev;
74         delete_list[dlist_len].inode = file->inode;
75         dlist_len++;
76
77         if (verbose > 3)
78                 rprintf(FINFO,"added %s to delete list\n", f_name(file));
79 }
80
81 static void delete_one(struct file_struct *f)
82 {
83         if (!S_ISDIR(f->mode)) {
84                 if (robust_unlink(f_name(f)) != 0) {
85                         rprintf(FERROR,"unlink %s : %s\n",f_name(f),strerror(errno));
86                 } else if (verbose) {
87                         rprintf(FINFO,"deleting %s\n",f_name(f));
88                 }
89         } else {    
90                 if (do_rmdir(f_name(f)) != 0) {
91                         if (errno != ENOTEMPTY && errno != EEXIST)
92                                 rprintf(FERROR,"rmdir %s : %s\n",f_name(f),strerror(errno));
93                 } else if (verbose) {
94                         rprintf(FINFO,"deleting directory %s\n",f_name(f));      
95                 }
96         }
97 }
98
99
100
101
102 /* this deletes any files on the receiving side that are not present
103    on the sending side. For version 1.6.4 I have changed the behaviour
104    to match more closely what most people seem to expect of this option */
105 static void delete_files(struct file_list *flist)
106 {
107         struct file_list *local_file_list;
108         int i, j;
109         char *name;
110         extern int module_id;
111         extern int max_delete;
112         static int deletion_count;
113
114         if (cvs_exclude)
115                 add_cvs_excludes();
116
117         if (io_error && !lp_ignore_errors(module_id)) {
118                 rprintf(FINFO,"IO error encountered - skipping file deletion\n");
119                 return;
120         }
121
122         for (j=0;j<flist->count;j++) {
123                 if (!S_ISDIR(flist->files[j]->mode) || 
124                     !(flist->files[j]->flags & FLAG_DELETE)) continue;
125
126                 if (remote_version < 19 &&
127                     delete_already_done(flist, j)) continue;
128
129                 name = strdup(f_name(flist->files[j]));
130
131                 if (!(local_file_list = send_file_list(-1,1,&name))) {
132                         free(name);
133                         continue;
134                 }
135
136                 if (verbose > 1)
137                         rprintf(FINFO,"deleting in %s\n", name);
138
139                 for (i=local_file_list->count-1;i>=0;i--) {
140                         if (max_delete && deletion_count > max_delete) break;
141                         if (!local_file_list->files[i]->basename) continue;
142                         if (remote_version < 19 &&
143                             S_ISDIR(local_file_list->files[i]->mode))
144                                 add_delete_entry(local_file_list->files[i]);
145                         if (-1 == flist_find(flist,local_file_list->files[i])) {
146                                 char *f = f_name(local_file_list->files[i]);
147                                 int k = strlen(f) - strlen(backup_suffix);
148 /* Hi Andrew, do we really need to play with backup_suffix here? */
149                                 if (make_backups && ((k <= 0) ||
150                                             (strcmp(f+k,backup_suffix) != 0))) {
151                                         (void) make_backup(f);
152                                 } else {
153                                         deletion_count++;
154                                         delete_one(local_file_list->files[i]);
155                                 }
156                         }
157                 }
158                 flist_free(local_file_list);
159                 free(name);
160         }
161 }
162
163
164 static int get_tmpname(char *fnametmp, char *fname)
165 {
166         char *f;
167
168         /* open tmp file */
169         if (tmpdir) {
170                 f = strrchr(fname,'/');
171                 if (f == NULL) 
172                         f = fname;
173                 else 
174                         f++;
175                 if (strlen(tmpdir)+strlen(f)+10 > MAXPATHLEN) {
176                         rprintf(FERROR,"filename too long\n");
177                         return 0;
178                 }
179                 slprintf(fnametmp,MAXPATHLEN, "%s/.%s.XXXXXX",tmpdir,f);
180                 return 1;
181         } 
182
183         f = strrchr(fname,'/');
184
185         if (strlen(fname)+9 > MAXPATHLEN) {
186                 rprintf(FERROR,"filename too long\n");
187                 return 0;
188         }
189
190         if (f) {
191                 *f = 0;
192                 slprintf(fnametmp,MAXPATHLEN,"%s/.%s.XXXXXX",
193                          fname,f+1);
194                 *f = '/';
195         } else {
196                 slprintf(fnametmp,MAXPATHLEN,".%s.XXXXXX",fname);
197         }
198
199         return 1;
200 }
201
202
203 static int receive_data(int f_in,struct map_struct *buf,int fd,char *fname,
204                         OFF_T total_size)
205 {
206         int i,n,remainder,len,count;
207         OFF_T offset = 0;
208         OFF_T offset2;
209         char *data;
210         static char file_sum1[MD4_SUM_LENGTH];
211         static char file_sum2[MD4_SUM_LENGTH];
212         char *map=NULL;
213         
214         count = read_int(f_in);
215         n = read_int(f_in);
216         remainder = read_int(f_in);
217         
218         sum_init();
219         
220         for (i=recv_token(f_in,&data); i != 0; i=recv_token(f_in,&data)) {
221
222                 show_progress(offset, total_size);
223
224                 if (i > 0) {
225                         extern int cleanup_got_literal;
226
227                         if (verbose > 3) {
228                                 rprintf(FINFO,"data recv %d at %.0f\n",
229                                         i,(double)offset);
230                         }
231
232                         stats.literal_data += i;
233                         cleanup_got_literal = 1;
234       
235                         sum_update(data,i);
236
237                         if (fd != -1 && write_file(fd,data,i) != i) {
238                                 rprintf(FERROR,"write failed on %s : %s\n",fname,strerror(errno));
239                                 exit_cleanup(RERR_FILEIO);
240                         }
241                         offset += i;
242                         continue;
243                 } 
244
245                 i = -(i+1);
246                 offset2 = i*(OFF_T)n;
247                 len = n;
248                 if (i == count-1 && remainder != 0)
249                         len = remainder;
250                 
251                 stats.matched_data += len;
252                 
253                 if (verbose > 3)
254                         rprintf(FINFO,"chunk[%d] of size %d at %.0f offset=%.0f\n",
255                                 i,len,(double)offset2,(double)offset);
256                 
257                 map = map_ptr(buf,offset2,len);
258                 
259                 see_token(map, len);
260                 sum_update(map,len);
261                 
262                 if (fd != -1 && write_file(fd,map,len) != len) {
263                         rprintf(FERROR,"write failed on %s : %s\n",
264                                 fname,strerror(errno));
265                         exit_cleanup(RERR_FILEIO);
266                 }
267                 offset += len;
268         }
269
270         end_progress();
271
272         if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
273                 rprintf(FERROR,"write failed on %s : %s\n",
274                         fname,strerror(errno));
275                 exit_cleanup(RERR_FILEIO);
276         }
277
278         sum_end(file_sum1);
279
280         if (remote_version >= 14) {
281                 read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
282                 if (verbose > 2) {
283                         rprintf(FINFO,"got file_sum\n");
284                 }
285                 if (fd != -1 && 
286                     memcmp(file_sum1,file_sum2,MD4_SUM_LENGTH) != 0) {
287                         return 0;
288                 }
289         }
290         return 1;
291 }
292
293
294 /* main routine for receiver process. Receiver process runs on the
295         same host as the generator process. */
296
297 int recv_files(int f_in,struct file_list *flist,char *local_name,int f_gen)
298 {  
299         int fd1,fd2;
300         STRUCT_STAT st;
301         char *fname;
302         char fnametmp[MAXPATHLEN];
303         char *fnamecmp;
304         char fnamecmpbuf[MAXPATHLEN];
305         struct map_struct *buf;
306         int i;
307         struct file_struct *file;
308         int phase=0;
309         int recv_ok;
310         extern struct stats stats;              
311         extern int preserve_perms;
312         extern int delete_after;
313         struct stats initial_stats;
314
315         if (verbose > 2) {
316                 rprintf(FINFO,"recv_files(%d) starting\n",flist->count);
317         }
318
319         if (!delete_after) {
320                 if (recurse && delete_mode && !local_name && flist->count>0) {
321                         delete_files(flist);
322                 }
323         }
324
325         while (1) {      
326                 cleanup_disable();
327
328                 i = read_int(f_in);
329                 if (i == -1) {
330                         if (phase==0 && remote_version >= 13) {
331                                 phase++;
332                                 csum_length = SUM_LENGTH;
333                                 if (verbose > 2)
334                                         rprintf(FINFO,"recv_files phase=%d\n",phase);
335                                 write_int(f_gen,-1);
336                                 continue;
337                         }
338                         break;
339                 }
340
341                 if (i < 0 || i >= flist->count) {
342                         rprintf(FERROR,"Invalid file index %d in recv_files (count=%d)\n", 
343                                 i, flist->count);
344                         exit_cleanup(RERR_PROTOCOL);
345                 }
346
347                 file = flist->files[i];
348                 fname = f_name(file);
349
350                 stats.num_transferred_files++;
351                 stats.total_transferred_size += file->length;
352
353                 if (local_name)
354                         fname = local_name;
355
356                 if (dry_run) {
357                         if (!am_server) {
358                                 log_transfer(file, fname);
359                         }
360                         continue;
361                 }
362
363                 initial_stats = stats;
364
365                 if (verbose > 2)
366                         rprintf(FINFO,"recv_files(%s)\n",fname);
367
368                 fnamecmp = fname;
369
370                 /* open the file */  
371                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
372
373                 if ((fd1 == -1) && (compare_dest != NULL)) {
374                         /* try the file at compare_dest instead */
375                         slprintf(fnamecmpbuf,MAXPATHLEN,"%s/%s",
376                                                 compare_dest,fname);
377                         fnamecmp = fnamecmpbuf;
378                         fd1 = do_open(fnamecmp, O_RDONLY, 0);
379                 }
380
381                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
382                         rprintf(FERROR,"fstat %s : %s\n",fnamecmp,strerror(errno));
383                         receive_data(f_in,NULL,-1,NULL,file->length);
384                         close(fd1);
385                         continue;
386                 }
387
388                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
389                         rprintf(FERROR,"%s : not a regular file (recv_files)\n",fnamecmp);
390                         receive_data(f_in,NULL,-1,NULL,file->length);
391                         close(fd1);
392                         continue;
393                 }
394
395                 if (fd1 != -1 && !preserve_perms) {
396                         /* if the file exists already and we aren't perserving
397                            presmissions then act as though the remote end sent
398                            us the file permissions we already have */
399                         file->mode = st.st_mode;
400                 }
401
402                 if (fd1 != -1 && st.st_size > 0) {
403                         buf = map_file(fd1,st.st_size);
404                         if (verbose > 2)
405                                 rprintf(FINFO,"recv mapped %s of size %.0f\n",fnamecmp,(double)st.st_size);
406                 } else {
407                         buf = NULL;
408                 }
409
410                 if (!get_tmpname(fnametmp,fname)) {
411                         if (buf) unmap_file(buf);
412                         if (fd1 != -1) close(fd1);
413                         continue;
414                 }
415
416                 /* mktemp is deliberately used here instead of mkstemp.
417                    because O_EXCL is used on the open, the race condition
418                    is not a problem or a security hole, and we want to
419                    control the access permissions on the created file. */
420                 if (NULL == do_mktemp(fnametmp)) {
421                         rprintf(FERROR,"mktemp %s failed\n",fnametmp);
422                         receive_data(f_in,buf,-1,NULL,file->length);
423                         if (buf) unmap_file(buf);
424                         if (fd1 != -1) close(fd1);
425                         continue;
426                 }
427
428                 /* we initially set the perms without the
429                    setuid/setgid bits to ensure that there is no race
430                    condition. They are then correctly updated after
431                    the lchown. Thanks to snabb@epipe.fi for pointing
432                    this out.  We also set it initially without group
433                    access because of a similar race condition. */
434                 fd2 = do_open(fnametmp,O_WRONLY|O_CREAT|O_EXCL,
435                               file->mode & INITACCESSPERMS);
436
437                 /* in most cases parent directories will already exist
438                    because their information should have been previously
439                    transferred, but that may not be the case with -R */
440                 if (fd2 == -1 && relative_paths && errno == ENOENT && 
441                     create_directory_path(fnametmp) == 0) {
442                         fd2 = do_open(fnametmp,O_WRONLY|O_CREAT|O_EXCL,
443                                       file->mode & INITACCESSPERMS);
444                 }
445                 if (fd2 == -1) {
446                         rprintf(FERROR,"cannot create %s : %s\n",fnametmp,strerror(errno));
447                         receive_data(f_in,buf,-1,NULL,file->length);
448                         if (buf) unmap_file(buf);
449                         if (fd1 != -1) close(fd1);
450                         continue;
451                 }
452       
453                 cleanup_set(fnametmp, fname, file, buf, fd1, fd2);
454
455                 if (!am_server) {
456                         log_transfer(file, fname);
457                 }
458
459                 /* recv file data */
460                 recv_ok = receive_data(f_in,buf,fd2,fname,file->length);
461
462                 log_recv(file, &initial_stats);
463                 
464                 if (buf) unmap_file(buf);
465                 if (fd1 != -1) {
466                         close(fd1);
467                 }
468                 close(fd2);
469                 
470                 if (verbose > 2)
471                         rprintf(FINFO,"renaming %s to %s\n",fnametmp,fname);
472
473                 finish_transfer(fname, fnametmp, file);
474
475                 cleanup_disable();
476
477                 if (!recv_ok) {
478                         if (csum_length == SUM_LENGTH) {
479                                 rprintf(FERROR,"ERROR: file corruption in %s. File changed during transfer?\n",
480                                         fname);
481                         } else {
482                                 if (verbose > 1)
483                                         rprintf(FINFO,"redoing %s(%d)\n",fname,i);
484                                 write_int(f_gen,i);
485                         }
486                 }
487         }
488
489         if (delete_after) {
490                 if (recurse && delete_mode && !local_name && flist->count>0) {
491                         delete_files(flist);
492                 }
493         }
494
495         if (preserve_hard_links)
496                 do_hard_links(flist);
497
498         /* now we need to fix any directory permissions that were 
499            modified during the transfer */
500         for (i = 0; i < flist->count; i++) {
501                 file = flist->files[i];
502                 if (!file->basename || !S_ISDIR(file->mode)) continue;
503                 recv_generator(local_name?local_name:f_name(file),flist,i,-1);
504         }
505
506         if (verbose > 2)
507                 rprintf(FINFO,"recv_files finished\n");
508         
509         return 0;
510 }
511