acc5da85722998c92c0565d1e740fc3430920eac
[rsync/rsync.git] / receiver.c
1 /* -*- c-file-style: "linux" -*-
2
3    Copyright (C) 1996-2000 by Andrew Tridgell
4    Copyright (C) Paul Mackerras 1996
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "rsync.h"
22
23 extern int verbose;
24 extern int recurse;
25 extern int delete_mode;
26 extern int delete_after;
27 extern int max_delete;
28 extern int csum_length;
29 extern struct stats stats;
30 extern int dry_run;
31 extern int am_server;
32 extern int relative_paths;
33 extern int preserve_hard_links;
34 extern int preserve_perms;
35 extern int cvs_exclude;
36 extern int io_error;
37 extern char *tmpdir;
38 extern char *compare_dest;
39 extern int make_backups;
40 extern int do_progress;
41 extern char *backup_dir;
42 extern char *backup_suffix;
43 extern int backup_suffix_len;
44 extern int cleanup_got_literal;
45 extern int module_id;
46 extern int ignore_errors;
47 extern int orig_umask;
48 extern int keep_partial;
49
50 static void delete_one(char *fn, int is_dir)
51 {
52         if (!is_dir) {
53                 if (robust_unlink(fn) != 0) {
54                         rprintf(FERROR, "delete_one: unlink %s failed: %s\n",
55                                 full_fname(fn), strerror(errno));
56                 } else if (verbose) {
57                         rprintf(FINFO, "deleting %s\n", fn);
58                 }
59         } else {
60                 if (do_rmdir(fn) != 0) {
61                         if (errno != ENOTEMPTY && errno != EEXIST) {
62                                 rprintf(FERROR, "delete_one: rmdir %s failed: %s\n",
63                                         full_fname(fn), strerror(errno));
64                         }
65                 } else if (verbose) {
66                         rprintf(FINFO, "deleting directory %s\n", fn);
67                 }
68         }
69 }
70
71
72 static int is_backup_file(char *fn)
73 {
74         int k = strlen(fn) - backup_suffix_len;
75         return k > 0 && strcmp(fn+k, backup_suffix) == 0;
76 }
77
78
79 /* This deletes any files on the receiving side that are not present
80  * on the sending side. */
81 void delete_files(struct file_list *flist)
82 {
83         struct file_list *local_file_list;
84         int i, j;
85         char *argv[1], fbuf[MAXPATHLEN];
86         static int deletion_count;
87
88         if (cvs_exclude)
89                 add_cvs_excludes();
90
91         if (io_error && !(lp_ignore_errors(module_id) || ignore_errors)) {
92                 rprintf(FINFO,"IO error encountered - skipping file deletion\n");
93                 return;
94         }
95
96         for (j = 0; j < flist->count; j++) {
97                 if (!(flist->files[j]->flags & FLAG_TOP_DIR)
98                     || !S_ISDIR(flist->files[j]->mode))
99                         continue;
100
101                 argv[0] = f_name_to(flist->files[j], fbuf);
102
103                 if (!(local_file_list = send_file_list(-1, 1, argv)))
104                         continue;
105
106                 if (verbose > 1)
107                         rprintf(FINFO, "deleting in %s\n", fbuf);
108
109                 for (i = local_file_list->count-1; i >= 0; i--) {
110                         if (max_delete && deletion_count > max_delete)
111                                 break;
112                         if (!local_file_list->files[i]->basename)
113                                 continue;
114                         if (flist_find(flist,local_file_list->files[i]) < 0) {
115                                 char *f = f_name(local_file_list->files[i]);
116                                 if (make_backups && (backup_dir || !is_backup_file(f))) {
117                                         (void) make_backup(f);
118                                         if (verbose)
119                                                 rprintf(FINFO, "deleting %s\n", f);
120                                 } else {
121                                         int mode = local_file_list->files[i]->mode;
122                                         delete_one(f, S_ISDIR(mode) != 0);
123                                 }
124                                 deletion_count++;
125                         }
126                 }
127                 flist_free(local_file_list);
128         }
129 }
130
131
132 /*
133  * get_tmpname() - create a tmp filename for a given filename
134  *
135  *   If a tmpdir is defined, use that as the directory to
136  *   put it in.  Otherwise, the tmp filename is in the same
137  *   directory as the given name.  Note that there may be no
138  *   directory at all in the given name!
139  *
140  *   The tmp filename is basically the given filename with a
141  *   dot prepended, and .XXXXXX appended (for mkstemp() to
142  *   put its unique gunk in).  Take care to not exceed
143  *   either the MAXPATHLEN or NAME_MAX, esp. the last, as
144  *   the basename basically becomes 8 chars longer. In that
145  *   case, the original name is shortened sufficiently to
146  *   make it all fit.
147  *
148  *   Of course, there's no real reason for the tmp name to
149  *   look like the original, except to satisfy us humans.
150  *   As long as it's unique, rsync will work.
151  */
152
153 static int get_tmpname(char *fnametmp, char *fname)
154 {
155         char *f;
156         int     length = 0;
157         int     maxname;
158
159         if (tmpdir) {
160                 /* Note: this can't overflow, so the return value is safe */
161                 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
162                 fnametmp[length++] = '/';
163                 fnametmp[length] = '\0';        /* always NULL terminated */
164         }
165
166         if ((f = strrchr(fname, '/')) != NULL) {
167                 ++f;
168                 if (!tmpdir) {
169                         length = f - fname;
170                         /* copy up to and including the slash */
171                         strlcpy(fnametmp, fname, length + 1);
172                 }
173         } else
174                 f = fname;
175         fnametmp[length++] = '.';
176         fnametmp[length] = '\0';                /* always NULL terminated */
177
178         maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
179
180         if (maxname < 1) {
181                 rprintf(FERROR, "temporary filename too long: %s\n", fname);
182                 fnametmp[0] = '\0';
183                 return 0;
184         }
185
186         strlcpy(fnametmp + length, f, maxname);
187         strcat(fnametmp + length, ".XXXXXX");
188
189         return 1;
190 }
191
192
193 static int receive_data(int f_in,struct map_struct *mapbuf,int fd,char *fname,
194                         OFF_T total_size)
195 {
196         int i;
197         struct sum_struct sum;
198         unsigned int len;
199         OFF_T offset = 0;
200         OFF_T offset2;
201         char *data;
202         static char file_sum1[MD4_SUM_LENGTH];
203         static char file_sum2[MD4_SUM_LENGTH];
204         char *map=NULL;
205
206         read_sum_head(f_in, &sum);
207
208         sum_init();
209
210         while ((i = recv_token(f_in, &data)) != 0) {
211                 if (do_progress)
212                         show_progress(offset, total_size);
213
214                 if (i > 0) {
215                         if (verbose > 3) {
216                                 rprintf(FINFO,"data recv %d at %.0f\n",
217                                         i,(double)offset);
218                         }
219
220                         stats.literal_data += i;
221                         cleanup_got_literal = 1;
222
223                         sum_update(data,i);
224
225                         if (fd != -1 && write_file(fd,data,i) != i) {
226                                 rprintf(FERROR, "write failed on %s: %s\n",
227                                         full_fname(fname), strerror(errno));
228                                 exit_cleanup(RERR_FILEIO);
229                         }
230                         offset += i;
231                         continue;
232                 }
233
234                 i = -(i+1);
235                 offset2 = i*(OFF_T)sum.blength;
236                 len = sum.blength;
237                 if (i == (int) sum.count-1 && sum.remainder != 0)
238                         len = sum.remainder;
239
240                 stats.matched_data += len;
241
242                 if (verbose > 3)
243                         rprintf(FINFO,"chunk[%d] of size %d at %.0f offset=%.0f\n",
244                                 i,len,(double)offset2,(double)offset);
245
246                 if (mapbuf) {
247                         map = map_ptr(mapbuf,offset2,len);
248
249                         see_token(map, len);
250                         sum_update(map,len);
251                 }
252
253                 if (fd != -1 && write_file(fd,map,len) != (int) len) {
254                         rprintf(FERROR, "write failed on %s: %s\n",
255                                 full_fname(fname), strerror(errno));
256                         exit_cleanup(RERR_FILEIO);
257                 }
258                 offset += len;
259         }
260
261         flush_write_file(fd);
262
263         if (do_progress)
264                 end_progress(total_size);
265
266         if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
267                 rprintf(FERROR, "write failed on %s: %s\n",
268                         full_fname(fname), strerror(errno));
269                 exit_cleanup(RERR_FILEIO);
270         }
271
272         sum_end(file_sum1);
273
274         read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
275         if (verbose > 2) {
276                 rprintf(FINFO,"got file_sum\n");
277         }
278         if (fd != -1 && memcmp(file_sum1,file_sum2,MD4_SUM_LENGTH) != 0) {
279                 return 0;
280         }
281         return 1;
282 }
283
284
285 /**
286  * main routine for receiver process.
287  *
288  * Receiver process runs on the same host as the generator process. */
289 int recv_files(int f_in,struct file_list *flist,char *local_name)
290 {
291         int fd1,fd2;
292         STRUCT_STAT st;
293         char *fname, fbuf[MAXPATHLEN];
294         char template[MAXPATHLEN];
295         char fnametmp[MAXPATHLEN];
296         char *fnamecmp;
297         char fnamecmpbuf[MAXPATHLEN];
298         struct map_struct *mapbuf;
299         int i;
300         struct file_struct *file;
301         int phase=0;
302         int recv_ok;
303         struct stats initial_stats;
304
305         if (verbose > 2) {
306                 rprintf(FINFO,"recv_files(%d) starting\n",flist->count);
307         }
308
309         if (flist->hlink_pool) {
310                 pool_destroy(flist->hlink_pool);
311                 flist->hlink_pool = NULL;
312         }
313
314         while (1) {
315                 cleanup_disable();
316
317                 i = read_int(f_in);
318                 if (i == -1) {
319                         if (phase == 0) {
320                                 phase++;
321                                 csum_length = SUM_LENGTH;
322                                 if (verbose > 2)
323                                         rprintf(FINFO,"recv_files phase=%d\n",phase);
324                                 send_msg(MSG_DONE, "", 0);
325                                 continue;
326                         }
327                         break;
328                 }
329
330                 if (i < 0 || i >= flist->count) {
331                         rprintf(FERROR,"Invalid file index %d in recv_files (count=%d)\n",
332                                 i, flist->count);
333                         exit_cleanup(RERR_PROTOCOL);
334                 }
335
336                 file = flist->files[i];
337
338                 stats.current_file_index = i;
339                 stats.num_transferred_files++;
340                 stats.total_transferred_size += file->length;
341                 cleanup_got_literal = 0;
342
343                 if (local_name)
344                         fname = local_name;
345                 else
346                         fname = f_name_to(file, fbuf);
347
348                 if (dry_run) {
349                         if (!am_server && verbose) {    /* log transfer */
350                                 rprintf(FINFO, "%s\n", fname);
351                         }
352                         continue;
353                 }
354
355                 initial_stats = stats;
356
357                 if (verbose > 2)
358                         rprintf(FINFO,"recv_files(%s)\n",fname);
359
360                 fnamecmp = fname;
361
362                 /* open the file */
363                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
364
365                 if (fd1 == -1 && compare_dest != NULL) {
366                         /* try the file at compare_dest instead */
367                         pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
368                                  compare_dest, fname);
369                         fnamecmp = fnamecmpbuf;
370                         fd1 = do_open(fnamecmp, O_RDONLY, 0);
371                 }
372
373                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
374                         rprintf(FERROR, "fstat %s failed: %s\n",
375                                 full_fname(fnamecmp), strerror(errno));
376                         receive_data(f_in,NULL,-1,NULL,file->length);
377                         close(fd1);
378                         continue;
379                 }
380
381                 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
382                         /* this special handling for directories
383                          * wouldn't be necessary if robust_rename()
384                          * and the underlying robust_unlink could cope
385                          * with directories
386                          */
387                         rprintf(FERROR,"recv_files: %s is a directory\n",
388                                 full_fname(fnamecmp));
389                         receive_data(f_in, NULL, -1, NULL, file->length);
390                         close(fd1);
391                         continue;
392                 }
393
394                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
395                         close(fd1);
396                         fd1 = -1;
397                         mapbuf = NULL;
398                 }
399
400                 if (fd1 != -1 && !preserve_perms) {
401                         /* if the file exists already and we aren't preserving
402                          * permissions then act as though the remote end sent
403                          * us the file permissions we already have */
404                         file->mode = st.st_mode;
405                 }
406
407                 if (fd1 != -1 && st.st_size > 0) {
408                         mapbuf = map_file(fd1,st.st_size);
409                         if (verbose > 2)
410                                 rprintf(FINFO,"recv mapped %s of size %.0f\n",fnamecmp,(double)st.st_size);
411                 } else
412                         mapbuf = NULL;
413
414                 if (!get_tmpname(fnametmp,fname)) {
415                         if (mapbuf) unmap_file(mapbuf);
416                         if (fd1 != -1) close(fd1);
417                         continue;
418                 }
419
420                 strlcpy(template, fnametmp, sizeof template);
421
422                 /* we initially set the perms without the
423                  * setuid/setgid bits to ensure that there is no race
424                  * condition. They are then correctly updated after
425                  * the lchown. Thanks to snabb@epipe.fi for pointing
426                  * this out.  We also set it initially without group
427                  * access because of a similar race condition. */
428                 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
429
430                 /* in most cases parent directories will already exist
431                  * because their information should have been previously
432                  * transferred, but that may not be the case with -R */
433                 if (fd2 == -1 && relative_paths && errno == ENOENT &&
434                     create_directory_path(fnametmp, orig_umask) == 0) {
435                         strlcpy(fnametmp, template, sizeof fnametmp);
436                         fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
437                 }
438                 if (fd2 == -1) {
439                         rprintf(FERROR, "mkstemp %s failed: %s\n",
440                                 full_fname(fnametmp), strerror(errno));
441                         receive_data(f_in,mapbuf,-1,NULL,file->length);
442                         if (mapbuf) unmap_file(mapbuf);
443                         if (fd1 != -1) close(fd1);
444                         continue;
445                 }
446
447                 cleanup_set(fnametmp, fname, file, mapbuf, fd1, fd2);
448
449                 if (!am_server && verbose) {    /* log transfer */
450                         rprintf(FINFO, "%s\n", fname);
451                 }
452
453                 /* recv file data */
454                 recv_ok = receive_data(f_in,mapbuf,fd2,fname,file->length);
455
456                 log_recv(file, &initial_stats);
457
458                 if (mapbuf) unmap_file(mapbuf);
459                 if (fd1 != -1) {
460                         close(fd1);
461                 }
462                 if (close(fd2) < 0) {
463                         rprintf(FERROR, "close failed on %s: %s\n",
464                                 full_fname(fnametmp), strerror(errno));
465                         exit_cleanup(RERR_FILEIO);
466                 }
467
468                 if (verbose > 2)
469                         rprintf(FINFO,"renaming %s to %s\n",fnametmp,fname);
470
471                 if (recv_ok || keep_partial)
472                         finish_transfer(fname, fnametmp, file, recv_ok);
473                 else
474                         do_unlink(fnametmp);
475
476                 cleanup_disable();
477
478                 if (!recv_ok) {
479                         if (csum_length == SUM_LENGTH) {
480                                 rprintf(FERROR,"ERROR: file corruption in %s. File changed during transfer?\n",
481                                         full_fname(fname));
482                         } else {
483                                 char buf[4];
484                                 if (verbose > 1)
485                                         rprintf(FINFO,"redoing %s(%d)\n",fname,i);
486                                 SIVAL(buf, 0, i);
487                                 send_msg(MSG_REDO, buf, 4);
488                         }
489                 }
490         }
491
492         if (delete_after && recurse && delete_mode && !local_name
493             && flist->count > 0)
494                 delete_files(flist);
495
496         if (verbose > 2)
497                 rprintf(FINFO,"recv_files finished\n");
498
499         return 0;
500 }