Should always call finish_transfer() for inplace handling, just like
[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 read_batch;
32 extern int batch_gen_fd;
33 extern int am_server;
34 extern int relative_paths;
35 extern int keep_dirlinks;
36 extern int preserve_hard_links;
37 extern int preserve_perms;
38 extern int cvs_exclude;
39 extern int io_error;
40 extern char *tmpdir;
41 extern char *compare_dest;
42 extern int make_backups;
43 extern int do_progress;
44 extern char *backup_dir;
45 extern char *backup_suffix;
46 extern int backup_suffix_len;
47 extern int cleanup_got_literal;
48 extern int module_id;
49 extern int ignore_errors;
50 extern int orig_umask;
51 extern int keep_partial;
52 extern int checksum_seed;
53 extern int inplace;
54
55 extern struct exclude_list_struct server_exclude_list;
56
57
58 static void delete_one(char *fn, int is_dir)
59 {
60         if (!is_dir) {
61                 if (robust_unlink(fn) != 0) {
62                         rsyserr(FERROR, errno, "delete_one: unlink %s failed",
63                                 full_fname(fn));
64                 } else if (verbose)
65                         rprintf(FINFO, "deleting %s\n", fn);
66         } else {
67                 if (do_rmdir(fn) != 0) {
68                         if (errno == ENOTDIR && keep_dirlinks) {
69                                 delete_one(fn, 0);
70                                 return;
71                         }
72                         if (errno != ENOTEMPTY && errno != EEXIST) {
73                                 rsyserr(FERROR, errno,
74                                         "delete_one: rmdir %s failed",
75                                         full_fname(fn));
76                         }
77                 } else if (verbose)
78                         rprintf(FINFO, "deleting directory %s\n", fn);
79         }
80 }
81
82
83 static int is_backup_file(char *fn)
84 {
85         int k = strlen(fn) - backup_suffix_len;
86         return k > 0 && strcmp(fn+k, backup_suffix) == 0;
87 }
88
89
90 /* This deletes any files on the receiving side that are not present
91  * on the sending side. */
92 void delete_files(struct file_list *flist)
93 {
94         struct file_list *local_file_list;
95         int i, j;
96         char *argv[1], fbuf[MAXPATHLEN];
97         static int deletion_count;
98
99         if (cvs_exclude)
100                 add_cvs_excludes();
101
102         if (io_error && !(lp_ignore_errors(module_id) || ignore_errors)) {
103                 rprintf(FINFO,"IO error encountered - skipping file deletion\n");
104                 return;
105         }
106
107         for (j = 0; j < flist->count; j++) {
108                 if (!(flist->files[j]->flags & FLAG_TOP_DIR)
109                     || !S_ISDIR(flist->files[j]->mode))
110                         continue;
111
112                 argv[0] = f_name_to(flist->files[j], fbuf);
113
114                 if (!(local_file_list = send_file_list(-1, 1, argv)))
115                         continue;
116
117                 if (verbose > 1)
118                         rprintf(FINFO, "deleting in %s\n", fbuf);
119
120                 for (i = local_file_list->count-1; i >= 0; i--) {
121                         if (max_delete && deletion_count > max_delete)
122                                 break;
123                         if (!local_file_list->files[i]->basename)
124                                 continue;
125                         if (flist_find(flist,local_file_list->files[i]) < 0) {
126                                 char *f = f_name(local_file_list->files[i]);
127                                 if (make_backups && (backup_dir || !is_backup_file(f))) {
128                                         make_backup(f);
129                                         if (verbose)
130                                                 rprintf(FINFO, "deleting %s\n", f);
131                                 } else {
132                                         int mode = local_file_list->files[i]->mode;
133                                         delete_one(f, S_ISDIR(mode) != 0);
134                                 }
135                                 deletion_count++;
136                         }
137                 }
138                 flist_free(local_file_list);
139         }
140 }
141
142
143 /*
144  * get_tmpname() - create a tmp filename for a given filename
145  *
146  *   If a tmpdir is defined, use that as the directory to
147  *   put it in.  Otherwise, the tmp filename is in the same
148  *   directory as the given name.  Note that there may be no
149  *   directory at all in the given name!
150  *
151  *   The tmp filename is basically the given filename with a
152  *   dot prepended, and .XXXXXX appended (for mkstemp() to
153  *   put its unique gunk in).  Take care to not exceed
154  *   either the MAXPATHLEN or NAME_MAX, esp. the last, as
155  *   the basename basically becomes 8 chars longer. In that
156  *   case, the original name is shortened sufficiently to
157  *   make it all fit.
158  *
159  *   Of course, there's no real reason for the tmp name to
160  *   look like the original, except to satisfy us humans.
161  *   As long as it's unique, rsync will work.
162  */
163
164 static int get_tmpname(char *fnametmp, char *fname)
165 {
166         char *f;
167         int     length = 0;
168         int     maxname;
169
170         if (tmpdir) {
171                 /* Note: this can't overflow, so the return value is safe */
172                 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
173                 fnametmp[length++] = '/';
174                 fnametmp[length] = '\0';        /* always NULL terminated */
175         }
176
177         if ((f = strrchr(fname, '/')) != NULL) {
178                 ++f;
179                 if (!tmpdir) {
180                         length = f - fname;
181                         /* copy up to and including the slash */
182                         strlcpy(fnametmp, fname, length + 1);
183                 }
184         } else
185                 f = fname;
186         fnametmp[length++] = '.';
187         fnametmp[length] = '\0';                /* always NULL terminated */
188
189         maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
190
191         if (maxname < 1) {
192                 rprintf(FERROR, "temporary filename too long: %s\n", fname);
193                 fnametmp[0] = '\0';
194                 return 0;
195         }
196
197         strlcpy(fnametmp + length, f, maxname);
198         strcat(fnametmp + length, ".XXXXXX");
199
200         return 1;
201 }
202
203
204 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
205                         char *fname, int fd, OFF_T total_size)
206 {
207         static char file_sum1[MD4_SUM_LENGTH];
208         static char file_sum2[MD4_SUM_LENGTH];
209         struct map_struct *mapbuf;
210         struct sum_struct sum;
211         unsigned int len;
212         OFF_T offset = 0;
213         OFF_T offset2;
214         char *data;
215         int i;
216         char *map = NULL;
217
218         read_sum_head(f_in, &sum);
219
220         if (fd_r >= 0 && size_r > 0) {
221                 mapbuf = map_file(fd_r, size_r, sum.blength);
222                 if (verbose > 2) {
223                         rprintf(FINFO, "recv mapped %s of size %.0f\n",
224                                 fname_r, (double)size_r);
225                 }
226         } else
227                 mapbuf = NULL;
228
229         sum_init(checksum_seed);
230
231         while ((i = recv_token(f_in, &data)) != 0) {
232                 if (do_progress)
233                         show_progress(offset, total_size);
234
235                 if (i > 0) {
236                         if (verbose > 3) {
237                                 rprintf(FINFO,"data recv %d at %.0f\n",
238                                         i,(double)offset);
239                         }
240
241                         stats.literal_data += i;
242                         cleanup_got_literal = 1;
243
244                         sum_update(data,i);
245
246                         if (fd != -1 && write_file(fd,data,i) != i) {
247                                 rsyserr(FERROR, errno, "write failed on %s",
248                                         full_fname(fname));
249                                 exit_cleanup(RERR_FILEIO);
250                         }
251                         offset += i;
252                         continue;
253                 }
254
255                 i = -(i+1);
256                 offset2 = i*(OFF_T)sum.blength;
257                 len = sum.blength;
258                 if (i == (int)sum.count-1 && sum.remainder != 0)
259                         len = sum.remainder;
260
261                 stats.matched_data += len;
262
263                 if (verbose > 3)
264                         rprintf(FINFO,"chunk[%d] of size %d at %.0f offset=%.0f\n",
265                                 i,len,(double)offset2,(double)offset);
266
267                 if (mapbuf) {
268                         map = map_ptr(mapbuf,offset2,len);
269
270                         see_token(map, len);
271                         sum_update(map,len);
272                 }
273
274                 if (!inplace || offset != offset2) {
275                         if (fd != -1 && write_file(fd, map, len) != (int)len) {
276                                 rsyserr(FERROR, errno, "write failed on %s",
277                                         full_fname(fname));
278                                 exit_cleanup(RERR_FILEIO);
279                         }
280                 } else {
281                         flush_write_file(fd);
282                         if (do_lseek(fd,(OFF_T)len,SEEK_CUR) != offset+len) {
283                                 rprintf(FERROR, "lseek failed on %s: %s, %lli, %lli, %i\n",
284                                         full_fname(fname), strerror(errno),
285                                         do_lseek(fd, 0, SEEK_CUR),
286                                         offset + len, i);
287                                 exit_cleanup(RERR_FILEIO);
288                         }
289                 }
290                 offset += len;
291         }
292
293         flush_write_file(fd);
294
295 #ifdef HAVE_FTRUNCATE
296         if (inplace)
297                 ftruncate(fd, offset);
298 #endif
299
300         if (do_progress)
301                 end_progress(total_size);
302
303         if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
304                 rsyserr(FERROR, errno, "write failed on %s",
305                         full_fname(fname));
306                 exit_cleanup(RERR_FILEIO);
307         }
308
309         sum_end(file_sum1);
310
311         if (mapbuf)
312                 unmap_file(mapbuf);
313
314         read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
315         if (verbose > 2)
316                 rprintf(FINFO,"got file_sum\n");
317         if (fd != -1 && memcmp(file_sum1, file_sum2, MD4_SUM_LENGTH) != 0)
318                 return 0;
319         return 1;
320 }
321
322
323 static void discard_receive_data(int f_in, OFF_T length)
324 {
325         receive_data(f_in, NULL, -1, 0, NULL, -1, length);
326 }
327
328
329 /**
330  * main routine for receiver process.
331  *
332  * Receiver process runs on the same host as the generator process. */
333 int recv_files(int f_in, struct file_list *flist, char *local_name)
334 {
335         int next_gen_i = -1;
336         int fd1,fd2;
337         STRUCT_STAT st;
338         char *fname, fbuf[MAXPATHLEN];
339         char template[MAXPATHLEN];
340         char fnametmp[MAXPATHLEN];
341         char *fnamecmp;
342         char fnamecmpbuf[MAXPATHLEN];
343         struct file_struct *file;
344         struct stats initial_stats;
345         int save_make_backups = make_backups;
346         int i, recv_ok, phase = 0;
347
348         if (verbose > 2)
349                 rprintf(FINFO,"recv_files(%d) starting\n",flist->count);
350
351         if (flist->hlink_pool) {
352                 pool_destroy(flist->hlink_pool);
353                 flist->hlink_pool = NULL;
354         }
355
356         while (1) {
357                 cleanup_disable();
358
359                 i = read_int(f_in);
360                 if (i == -1) {
361                         if (read_batch) {
362                                 if (next_gen_i != flist->count)
363                                         while (read_int(batch_gen_fd) != -1) {}
364                                 next_gen_i = -1;
365                         }
366
367                         if (phase)
368                                 break;
369
370                         phase = 1;
371                         csum_length = SUM_LENGTH;
372                         if (verbose > 2)
373                                 rprintf(FINFO, "recv_files phase=%d\n", phase);
374                         send_msg(MSG_DONE, "", 0);
375                         if (keep_partial)
376                                 make_backups = 0; /* prevents double backup */
377                         continue;
378                 }
379
380                 if (i < 0 || i >= flist->count) {
381                         rprintf(FERROR,"Invalid file index %d in recv_files (count=%d)\n",
382                                 i, flist->count);
383                         exit_cleanup(RERR_PROTOCOL);
384                 }
385
386                 file = flist->files[i];
387
388                 stats.current_file_index = i;
389                 stats.num_transferred_files++;
390                 stats.total_transferred_size += file->length;
391                 cleanup_got_literal = 0;
392
393                 if (local_name)
394                         fname = local_name;
395                 else
396                         fname = f_name_to(file, fbuf);
397
398                 if (dry_run) {
399                         if (!am_server && verbose)
400                                 rprintf(FINFO, "%s\n", fname);
401                         continue;
402                 }
403
404                 initial_stats = stats;
405
406                 if (verbose > 2)
407                         rprintf(FINFO,"recv_files(%s)\n",fname);
408
409                 fnamecmp = fname;
410
411                 if (read_batch) {
412                         while (i > next_gen_i) {
413                                 next_gen_i = read_int(batch_gen_fd);
414                                 if (next_gen_i == -1)
415                                         next_gen_i = flist->count;
416                         }
417                         if (i < next_gen_i) {
418                                 rprintf(FINFO, "skipping update for \"%s\"\n",
419                                         fname);
420                                 discard_receive_data(f_in, file->length);
421                                 continue;
422                         }
423                 }
424
425                 if (server_exclude_list.head
426                     && check_exclude(&server_exclude_list, fname,
427                                      S_ISDIR(file->mode)) < 0) {
428                         if (verbose) {
429                                 rprintf(FINFO,
430                                         "skipping server-excluded update for \"%s\"\n",
431                                         fname);
432                         }
433                         discard_receive_data(f_in, file->length);
434                         continue;
435                 }
436
437                 /* open the file */
438                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
439
440                 if (fd1 == -1 && compare_dest != NULL) {
441                         /* try the file at compare_dest instead */
442                         pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
443                                  compare_dest, fname);
444                         fnamecmp = fnamecmpbuf;
445                         fd1 = do_open(fnamecmp, O_RDONLY, 0);
446                 }
447
448                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
449                         rsyserr(FERROR, errno, "fstat %s failed",
450                                 full_fname(fnamecmp));
451                         discard_receive_data(f_in, file->length);
452                         close(fd1);
453                         continue;
454                 }
455
456                 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
457                         /* this special handling for directories
458                          * wouldn't be necessary if robust_rename()
459                          * and the underlying robust_unlink could cope
460                          * with directories
461                          */
462                         rprintf(FERROR,"recv_files: %s is a directory\n",
463                                 full_fname(fnamecmp));
464                         discard_receive_data(f_in, file->length);
465                         close(fd1);
466                         continue;
467                 }
468
469                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
470                         close(fd1);
471                         fd1 = -1;
472                 }
473
474                 if (fd1 != -1 && !preserve_perms) {
475                         /* if the file exists already and we aren't preserving
476                          * permissions then act as though the remote end sent
477                          * us the file permissions we already have */
478                         file->mode = st.st_mode;
479                 }
480
481                 /* We now check to see if we are writing file "inplace" */
482                 if (inplace)  {
483                         fd2 = do_open(fnamecmp, O_WRONLY|O_CREAT, 0);
484                         if (fd2 == -1) {
485                                 rsyserr(FERROR, errno, "open %s failed",
486                                         full_fname(fnamecmp));
487                                 discard_receive_data(f_in, file->length);
488                                 if (fd1 != -1)
489                                         close(fd1);
490                                 continue;
491                         }
492                 } else {
493                         if (!get_tmpname(fnametmp,fname)) {
494                                 discard_receive_data(f_in, file->length);
495                                 if (fd1 != -1)
496                                         close(fd1);
497                                 continue;
498                         }
499
500                         strlcpy(template, fnametmp, sizeof template);
501
502                         /* we initially set the perms without the
503                          * setuid/setgid bits to ensure that there is no race
504                          * condition. They are then correctly updated after
505                          * the lchown. Thanks to snabb@epipe.fi for pointing
506                          * this out.  We also set it initially without group
507                          * access because of a similar race condition. */
508                         fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
509
510                         /* in most cases parent directories will already exist
511                          * because their information should have been previously
512                          * transferred, but that may not be the case with -R */
513                         if (fd2 == -1 && relative_paths && errno == ENOENT
514                             && create_directory_path(fnametmp, orig_umask) == 0) {
515                                 strlcpy(fnametmp, template, sizeof fnametmp);
516                                 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
517                         }
518                         if (fd2 == -1) {
519                                 rsyserr(FERROR, errno, "mkstemp %s failed",
520                                         full_fname(fnametmp));
521                                 discard_receive_data(f_in, file->length);
522                                 if (fd1 != -1)
523                                         close(fd1);
524                                 continue;
525                         }
526
527                         cleanup_set(fnametmp, fname, file, fd1, fd2);
528                 }
529
530                 if (!am_server && verbose)
531                         rprintf(FINFO, "%s\n", fname);
532
533                 /* recv file data */
534                 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
535                                        fname, fd2, file->length);
536
537                 log_recv(file, &initial_stats);
538
539                 if (fd1 != -1)
540                         close(fd1);
541                 if (close(fd2) < 0) {
542                         rsyserr(FERROR, errno, "close failed on %s",
543                                 full_fname(fnametmp));
544                         exit_cleanup(RERR_FILEIO);
545                 }
546
547                 if (recv_ok || keep_partial || inplace)
548                         finish_transfer(fname, fnametmp, file, recv_ok);
549                 else
550                         do_unlink(fnametmp);
551
552                 cleanup_disable();
553
554                 if (!recv_ok) {
555                         int msgtype = csum_length == SUM_LENGTH || read_batch ?
556                                 FERROR : FINFO;
557                         if (msgtype == FERROR || verbose) {
558                                 char *errstr, *redostr;
559                                 char *keptstr = keep_partial || inplace ?
560                                         "retain" : "discard";
561                                 if (msgtype == FERROR) {
562                                         errstr = "ERROR";
563                                         redostr = "";
564                                 } else {
565                                         errstr = "WARNING";
566                                         redostr = " (will try again)";
567                                 }
568                                 rprintf(msgtype,
569                                         "%s: %s failed verification -- update %sed%s.\n",
570                                         errstr, fname, keptstr, redostr);
571                         }
572                         if (csum_length != SUM_LENGTH) {
573                                 char buf[4];
574                                 SIVAL(buf, 0, i);
575                                 send_msg(MSG_REDO, buf, 4);
576                         }
577                 }
578         }
579         make_backups = save_make_backups;
580
581         if (delete_after && recurse && !local_name && flist->count > 0)
582                 delete_files(flist);
583
584         if (verbose > 2)
585                 rprintf(FINFO,"recv_files finished\n");
586
587         return 0;
588 }