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