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