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