Saved 9 more bytes per file in a typical transfer by making the length
[rsync/rsync.git] / receiver.c
... / ...
CommitLineData
1/*
2 * Routines only used by the receiving process.
3 *
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003, 2004, 2005, 2006 Wayne Davison
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
21 */
22
23#include "rsync.h"
24
25extern int verbose;
26extern int do_xfers;
27extern int am_server;
28extern int do_progress;
29extern int log_before_transfer;
30extern int stdout_format_has_i;
31extern int logfile_format_has_i;
32extern int csum_length;
33extern int read_batch;
34extern int write_batch;
35extern int batch_gen_fd;
36extern int protocol_version;
37extern int relative_paths;
38extern int preserve_hard_links;
39extern int preserve_perms;
40extern int basis_dir_cnt;
41extern int make_backups;
42extern int flist_extra_ndx;
43extern int cleanup_got_literal;
44extern int remove_source_files;
45extern int append_mode;
46extern int sparse_files;
47extern int keep_partial;
48extern int checksum_seed;
49extern int inplace;
50extern int delay_updates;
51extern struct stats stats;
52extern char *stdout_format;
53extern char *tmpdir;
54extern char *partial_dir;
55extern char *basis_dir[];
56extern struct file_list *the_file_list;
57extern struct filter_list_struct server_filter_list;
58
59static struct bitbag *delayed_bits = NULL;
60static int phase = 0;
61/* We're either updating the basis file or an identical copy: */
62static int updating_basis;
63
64
65/*
66 * get_tmpname() - create a tmp filename for a given filename
67 *
68 * If a tmpdir is defined, use that as the directory to
69 * put it in. Otherwise, the tmp filename is in the same
70 * directory as the given name. Note that there may be no
71 * directory at all in the given name!
72 *
73 * The tmp filename is basically the given filename with a
74 * dot prepended, and .XXXXXX appended (for mkstemp() to
75 * put its unique gunk in). Take care to not exceed
76 * either the MAXPATHLEN or NAME_MAX, esp. the last, as
77 * the basename basically becomes 8 chars longer. In that
78 * case, the original name is shortened sufficiently to
79 * make it all fit.
80 *
81 * Of course, there's no real reason for the tmp name to
82 * look like the original, except to satisfy us humans.
83 * As long as it's unique, rsync will work.
84 */
85
86int get_tmpname(char *fnametmp, char *fname)
87{
88 int maxname, added, length = 0;
89 char *f;
90
91 if (tmpdir) {
92 /* Note: this can't overflow, so the return value is safe */
93 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
94 fnametmp[length++] = '/';
95 }
96
97 if ((f = strrchr(fname, '/')) != NULL) {
98 ++f;
99 if (!tmpdir) {
100 length = f - fname;
101 /* copy up to and including the slash */
102 strlcpy(fnametmp, fname, length + 1);
103 }
104 } else
105 f = fname;
106 fnametmp[length++] = '.';
107
108 /* The maxname value is bufsize, and includes space for the '\0'.
109 * (Note that NAME_MAX get -8 for the leading '.' above.) */
110 maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
111
112 if (maxname < 1) {
113 rprintf(FERROR, "temporary filename too long: %s\n", fname);
114 fnametmp[0] = '\0';
115 return 0;
116 }
117
118 added = strlcpy(fnametmp + length, f, maxname);
119 if (added >= maxname)
120 added = maxname - 1;
121 memcpy(fnametmp + length + added, ".XXXXXX", 8);
122
123 return 1;
124}
125
126
127static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
128 char *fname, int fd, OFF_T total_size)
129{
130 static char file_sum1[MD4_SUM_LENGTH];
131 static char file_sum2[MD4_SUM_LENGTH];
132 struct map_struct *mapbuf;
133 struct sum_struct sum;
134 int32 len;
135 OFF_T offset = 0;
136 OFF_T offset2;
137 char *data;
138 int32 i;
139 char *map = NULL;
140
141 read_sum_head(f_in, &sum);
142
143 if (fd_r >= 0 && size_r > 0) {
144 int32 read_size = MAX(sum.blength * 2, 16*1024);
145 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
146 if (verbose > 2) {
147 rprintf(FINFO, "recv mapped %s of size %.0f\n",
148 fname_r, (double)size_r);
149 }
150 } else
151 mapbuf = NULL;
152
153 sum_init(checksum_seed);
154
155 if (append_mode) {
156 OFF_T j;
157 sum.flength = (OFF_T)sum.count * sum.blength;
158 if (sum.remainder)
159 sum.flength -= sum.blength - sum.remainder;
160 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
161 if (do_progress)
162 show_progress(offset, total_size);
163 sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
164 CHUNK_SIZE);
165 offset = j;
166 }
167 if (offset < sum.flength) {
168 int32 len = (int32)(sum.flength - offset);
169 if (do_progress)
170 show_progress(offset, total_size);
171 sum_update(map_ptr(mapbuf, offset, len), len);
172 offset = sum.flength;
173 }
174 if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) {
175 rsyserr(FERROR, errno, "lseek of %s returned %.0f, not %.0f",
176 full_fname(fname), (double)j, (double)offset);
177 exit_cleanup(RERR_FILEIO);
178 }
179 }
180
181 while ((i = recv_token(f_in, &data)) != 0) {
182 if (do_progress)
183 show_progress(offset, total_size);
184
185 if (i > 0) {
186 if (verbose > 3) {
187 rprintf(FINFO,"data recv %d at %.0f\n",
188 i,(double)offset);
189 }
190
191 stats.literal_data += i;
192 cleanup_got_literal = 1;
193
194 sum_update(data, i);
195
196 if (fd != -1 && write_file(fd,data,i) != i)
197 goto report_write_error;
198 offset += i;
199 continue;
200 }
201
202 i = -(i+1);
203 offset2 = i * (OFF_T)sum.blength;
204 len = sum.blength;
205 if (i == (int)sum.count-1 && sum.remainder != 0)
206 len = sum.remainder;
207
208 stats.matched_data += len;
209
210 if (verbose > 3) {
211 rprintf(FINFO,
212 "chunk[%d] of size %ld at %.0f offset=%.0f\n",
213 i, (long)len, (double)offset2, (double)offset);
214 }
215
216 if (mapbuf) {
217 map = map_ptr(mapbuf,offset2,len);
218
219 see_token(map, len);
220 sum_update(map, len);
221 }
222
223 if (updating_basis) {
224 if (offset == offset2 && fd != -1) {
225 OFF_T pos;
226 if (flush_write_file(fd) < 0)
227 goto report_write_error;
228 offset += len;
229 if ((pos = do_lseek(fd, len, SEEK_CUR)) != offset) {
230 rsyserr(FERROR, errno,
231 "lseek of %s returned %.0f, not %.0f",
232 full_fname(fname),
233 (double)pos, (double)offset);
234 exit_cleanup(RERR_FILEIO);
235 }
236 continue;
237 }
238 }
239 if (fd != -1 && map && write_file(fd, map, len) != (int)len)
240 goto report_write_error;
241 offset += len;
242 }
243
244 if (flush_write_file(fd) < 0)
245 goto report_write_error;
246
247#ifdef HAVE_FTRUNCATE
248 if (inplace && fd != -1)
249 ftruncate(fd, offset);
250#endif
251
252 if (do_progress)
253 end_progress(total_size);
254
255 if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
256 report_write_error:
257 rsyserr(FERROR, errno, "write failed on %s",
258 full_fname(fname));
259 exit_cleanup(RERR_FILEIO);
260 }
261
262 sum_end(file_sum1);
263
264 if (mapbuf)
265 unmap_file(mapbuf);
266
267 read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
268 if (verbose > 2)
269 rprintf(FINFO,"got file_sum\n");
270 if (fd != -1 && memcmp(file_sum1, file_sum2, MD4_SUM_LENGTH) != 0)
271 return 0;
272 return 1;
273}
274
275
276static void discard_receive_data(int f_in, OFF_T length)
277{
278 receive_data(f_in, NULL, -1, 0, NULL, -1, length);
279}
280
281static void handle_delayed_updates(struct file_list *flist, char *local_name)
282{
283 char *fname, *partialptr;
284 int i;
285
286 for (i = -1; (i = bitbag_next_bit(delayed_bits, i)) >= 0; ) {
287 struct file_struct *file = flist->files[i];
288 fname = local_name ? local_name : f_name(file, NULL);
289 if ((partialptr = partial_dir_fname(fname)) != NULL) {
290 if (make_backups && !make_backup(fname))
291 continue;
292 if (verbose > 2) {
293 rprintf(FINFO, "renaming %s to %s\n",
294 partialptr, fname);
295 }
296 /* We don't use robust_rename() here because the
297 * partial-dir must be on the same drive. */
298 if (do_rename(partialptr, fname) < 0) {
299 rsyserr(FERROR, errno,
300 "rename failed for %s (from %s)",
301 full_fname(fname), partialptr);
302 } else {
303 if (remove_source_files
304 || (preserve_hard_links && IS_HLINKED(file)))
305 send_msg_int(MSG_SUCCESS, i);
306 handle_partial_dir(partialptr, PDIR_DELETE);
307 }
308 }
309 }
310}
311
312static int get_next_gen_i(int batch_gen_fd, int next_gen_i, int desired_i)
313{
314 while (next_gen_i < desired_i) {
315 if (next_gen_i >= 0) {
316 rprintf(FINFO,
317 "(No batched update for%s \"%s\")\n",
318 phase ? " resend of" : "",
319 f_name(the_file_list->files[next_gen_i], NULL));
320 }
321 next_gen_i = read_int(batch_gen_fd);
322 if (next_gen_i == -1)
323 next_gen_i = the_file_list->count;
324 }
325 return next_gen_i;
326}
327
328
329/**
330 * main routine for receiver process.
331 *
332 * Receiver process runs on the same host as the generator process. */
333int 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 int iflags, xlen;
339 char *fname, fbuf[MAXPATHLEN];
340 char xname[MAXPATHLEN];
341 char fnametmp[MAXPATHLEN];
342 char *fnamecmp, *partialptr;
343 char fnamecmpbuf[MAXPATHLEN];
344 uchar fnamecmp_type;
345 struct file_struct *file;
346 struct stats initial_stats;
347 int save_make_backups = make_backups;
348 int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
349 enum logcode log_code = log_before_transfer ? FLOG : FINFO;
350 int max_phase = protocol_version >= 29 ? 2 : 1;
351 int i, recv_ok;
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 if (delay_updates)
362 delayed_bits = bitbag_create(flist->count);
363
364 updating_basis = inplace;
365
366 while (1) {
367 cleanup_disable();
368
369 i = read_int(f_in);
370 if (i == NDX_DONE) {
371 if (read_batch) {
372 get_next_gen_i(batch_gen_fd, next_gen_i,
373 flist->count);
374 next_gen_i = -1;
375 }
376 if (++phase > max_phase)
377 break;
378 csum_length = SUM_LENGTH;
379 if (verbose > 2)
380 rprintf(FINFO, "recv_files phase=%d\n", phase);
381 if (phase == 2 && delay_updates)
382 handle_delayed_updates(flist, local_name);
383 send_msg(MSG_DONE, "", 0);
384 if (keep_partial && !partial_dir)
385 make_backups = 0; /* prevents double backup */
386 if (append_mode) {
387 append_mode = 0;
388 sparse_files = 0;
389 }
390 continue;
391 }
392
393 iflags = read_item_attrs(f_in, -1, i, &fnamecmp_type,
394 xname, &xlen);
395 if (iflags == ITEM_IS_NEW) /* no-op packet */
396 continue;
397
398 file = flist->files[i];
399 fname = local_name ? local_name : f_name(file, fbuf);
400
401 if (verbose > 2)
402 rprintf(FINFO, "recv_files(%s)\n", fname);
403
404 if (!(iflags & ITEM_TRANSFER)) {
405 maybe_log_item(file, iflags, itemizing, xname);
406 continue;
407 }
408 if (phase == 2) {
409 rprintf(FERROR,
410 "got transfer request in phase 2 [%s]\n",
411 who_am_i());
412 exit_cleanup(RERR_PROTOCOL);
413 }
414
415 stats.current_file_index = i;
416 stats.num_transferred_files++;
417 stats.total_transferred_size += file->length;
418 cleanup_got_literal = 0;
419
420 if (server_filter_list.head
421 && check_filter(&server_filter_list, fname, 0) < 0) {
422 rprintf(FERROR, "attempt to hack rsync failed.\n");
423 exit_cleanup(RERR_PROTOCOL);
424 }
425
426 if (!do_xfers) { /* log the transfer */
427 log_item(FCLIENT, file, &stats, iflags, NULL);
428 if (read_batch)
429 discard_receive_data(f_in, file->length);
430 continue;
431 }
432 if (write_batch < 0) {
433 log_item(FINFO, file, &stats, iflags, NULL);
434 if (!am_server)
435 discard_receive_data(f_in, file->length);
436 continue;
437 }
438
439 if (read_batch) {
440 next_gen_i = get_next_gen_i(batch_gen_fd, next_gen_i, i);
441 if (i < next_gen_i) {
442 rprintf(FINFO,
443 "(Skipping batched update for \"%s\")\n",
444 fname);
445 discard_receive_data(f_in, file->length);
446 continue;
447 }
448 next_gen_i = -1;
449 }
450
451 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
452
453 if (protocol_version >= 29) {
454 switch (fnamecmp_type) {
455 case FNAMECMP_FNAME:
456 fnamecmp = fname;
457 break;
458 case FNAMECMP_PARTIAL_DIR:
459 fnamecmp = partialptr;
460 break;
461 case FNAMECMP_BACKUP:
462 fnamecmp = get_backup_name(fname);
463 break;
464 case FNAMECMP_FUZZY:
465 updating_basis = 0;
466 if (file->dirname) {
467 pathjoin(fnamecmpbuf, MAXPATHLEN,
468 file->dirname, xname);
469 fnamecmp = fnamecmpbuf;
470 } else
471 fnamecmp = xname;
472 break;
473 default:
474 updating_basis = 0;
475 if (fnamecmp_type >= basis_dir_cnt) {
476 rprintf(FERROR,
477 "invalid basis_dir index: %d.\n",
478 fnamecmp_type);
479 exit_cleanup(RERR_PROTOCOL);
480 }
481 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
482 basis_dir[fnamecmp_type], fname);
483 fnamecmp = fnamecmpbuf;
484 break;
485 }
486 if (!fnamecmp || (server_filter_list.head
487 && check_filter(&server_filter_list, fname, 0) < 0))
488 fnamecmp = fname;
489 } else {
490 /* Reminder: --inplace && --partial-dir are never
491 * enabled at the same time. */
492 if (inplace && make_backups) {
493 if (!(fnamecmp = get_backup_name(fname)))
494 fnamecmp = fname;
495 } else if (partial_dir && partialptr)
496 fnamecmp = partialptr;
497 else
498 fnamecmp = fname;
499 }
500
501 initial_stats = stats;
502
503 /* open the file */
504 fd1 = do_open(fnamecmp, O_RDONLY, 0);
505
506 if (fd1 == -1 && protocol_version < 29) {
507 if (fnamecmp != fname) {
508 fnamecmp = fname;
509 fd1 = do_open(fnamecmp, O_RDONLY, 0);
510 }
511
512 if (fd1 == -1 && basis_dir[0]) {
513 /* pre-29 allowed only one alternate basis */
514 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
515 basis_dir[0], fname);
516 fnamecmp = fnamecmpbuf;
517 fd1 = do_open(fnamecmp, O_RDONLY, 0);
518 }
519 }
520
521 if (fd1 == -1) {
522 st.st_mode = 0;
523 st.st_size = 0;
524 } else if (do_fstat(fd1,&st) != 0) {
525 rsyserr(FERROR, errno, "fstat %s failed",
526 full_fname(fnamecmp));
527 discard_receive_data(f_in, file->length);
528 close(fd1);
529 continue;
530 }
531
532 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
533 /* this special handling for directories
534 * wouldn't be necessary if robust_rename()
535 * and the underlying robust_unlink could cope
536 * with directories
537 */
538 rprintf(FERROR,"recv_files: %s is a directory\n",
539 full_fname(fnamecmp));
540 discard_receive_data(f_in, file->length);
541 close(fd1);
542 continue;
543 }
544
545 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
546 close(fd1);
547 fd1 = -1;
548 }
549
550 /* If we're not preserving permissions, change the file-list's
551 * mode based on the local permissions and some heuristics. */
552 if (!preserve_perms) {
553 int exists = fd1 != -1;
554 file->mode = dest_mode(file->mode, st.st_mode, exists);
555 }
556
557 /* We now check to see if we are writing the file "inplace" */
558 if (inplace) {
559 fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
560 if (fd2 == -1) {
561 rsyserr(FERROR, errno, "open %s failed",
562 full_fname(fname));
563 discard_receive_data(f_in, file->length);
564 if (fd1 != -1)
565 close(fd1);
566 continue;
567 }
568 } else {
569 if (!get_tmpname(fnametmp,fname)) {
570 discard_receive_data(f_in, file->length);
571 if (fd1 != -1)
572 close(fd1);
573 continue;
574 }
575
576 /* we initially set the perms without the
577 * setuid/setgid bits to ensure that there is no race
578 * condition. They are then correctly updated after
579 * the lchown. Thanks to snabb@epipe.fi for pointing
580 * this out. We also set it initially without group
581 * access because of a similar race condition. */
582 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
583
584 /* in most cases parent directories will already exist
585 * because their information should have been previously
586 * transferred, but that may not be the case with -R */
587 if (fd2 == -1 && relative_paths && errno == ENOENT
588 && create_directory_path(fnametmp) == 0) {
589 /* Get back to name with XXXXXX in it. */
590 get_tmpname(fnametmp, fname);
591 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
592 }
593 if (fd2 == -1) {
594 rsyserr(FERROR, errno, "mkstemp %s failed",
595 full_fname(fnametmp));
596 discard_receive_data(f_in, file->length);
597 if (fd1 != -1)
598 close(fd1);
599 continue;
600 }
601
602 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
603 }
604
605 /* log the transfer */
606 if (log_before_transfer)
607 log_item(FCLIENT, file, &initial_stats, iflags, NULL);
608 else if (!am_server && verbose && do_progress)
609 rprintf(FINFO, "%s\n", fname);
610
611 /* recv file data */
612 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
613 fname, fd2, file->length);
614
615 log_item(log_code, file, &initial_stats, iflags, NULL);
616
617 if (fd1 != -1)
618 close(fd1);
619 if (close(fd2) < 0) {
620 rsyserr(FERROR, errno, "close failed on %s",
621 full_fname(fnametmp));
622 exit_cleanup(RERR_FILEIO);
623 }
624
625 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
626 char *temp_copy_name;
627 if (partialptr == fname)
628 partialptr = temp_copy_name = NULL;
629 else if (*partial_dir == '/')
630 temp_copy_name = NULL;
631 else
632 temp_copy_name = partialptr;
633 finish_transfer(fname, fnametmp, temp_copy_name,
634 file, recv_ok, 1);
635 if (fnamecmp == partialptr) {
636 do_unlink(partialptr);
637 handle_partial_dir(partialptr, PDIR_DELETE);
638 }
639 } else if (keep_partial && partialptr
640 && handle_partial_dir(partialptr, PDIR_CREATE)) {
641 finish_transfer(partialptr, fnametmp, NULL,
642 file, recv_ok, !partial_dir);
643 if (delay_updates && recv_ok) {
644 bitbag_set_bit(delayed_bits, i);
645 recv_ok = -1;
646 }
647 } else {
648 partialptr = NULL;
649 do_unlink(fnametmp);
650 }
651
652 cleanup_disable();
653
654 if (recv_ok > 0) {
655 if (remove_source_files
656 || (preserve_hard_links && IS_HLINKED(file)))
657 send_msg_int(MSG_SUCCESS, i);
658 } else if (!recv_ok) {
659 enum logcode msgtype = phase || read_batch ? FERROR : FINFO;
660 if (msgtype == FERROR || verbose) {
661 char *errstr, *redostr, *keptstr;
662 if (!(keep_partial && partialptr) && !inplace)
663 keptstr = "discarded";
664 else if (partial_dir)
665 keptstr = "put into partial-dir";
666 else
667 keptstr = "retained";
668 if (msgtype == FERROR) {
669 errstr = "ERROR";
670 redostr = "";
671 } else {
672 errstr = "WARNING";
673 redostr = " (will try again)";
674 }
675 rprintf(msgtype,
676 "%s: %s failed verification -- update %s%s.\n",
677 errstr, fname, keptstr, redostr);
678 }
679 if (!phase)
680 send_msg_int(MSG_REDO, i);
681 }
682 }
683 make_backups = save_make_backups;
684
685 if (phase == 2 && delay_updates) /* for protocol_version < 29 */
686 handle_delayed_updates(flist, local_name);
687
688 if (verbose > 2)
689 rprintf(FINFO,"recv_files finished\n");
690
691 return 0;
692}