2 * Routines only used by the receiving process.
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2003-2007 Wayne Davison
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2 as
10 * published by the Free Software Foundation.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
27 extern int do_progress;
28 extern int inc_recurse;
29 extern int log_before_transfer;
30 extern int stdout_format_has_i;
31 extern int logfile_format_has_i;
32 extern int csum_length;
33 extern int read_batch;
34 extern int write_batch;
35 extern int batch_gen_fd;
36 extern int protocol_version;
37 extern int relative_paths;
38 extern int preserve_hard_links;
39 extern int preserve_perms;
40 extern int basis_dir_cnt;
41 extern int make_backups;
42 extern int cleanup_got_literal;
43 extern int remove_source_files;
44 extern int append_mode;
45 extern int sparse_files;
46 extern int keep_partial;
47 extern int checksum_seed;
49 extern int delay_updates;
50 extern mode_t orig_umask;
51 extern struct stats stats;
53 extern char *partial_dir;
54 extern char *basis_dir[];
55 extern struct file_list *cur_flist, *first_flist;
56 extern struct filter_list_struct server_filter_list;
58 static struct bitbag *delayed_bits = NULL;
59 static int phase = 0, redoing = 0;
60 /* We're either updating the basis file or an identical copy: */
61 static int updating_basis;
64 * get_tmpname() - create a tmp filename for a given filename
66 * If a tmpdir is defined, use that as the directory to
67 * put it in. Otherwise, the tmp filename is in the same
68 * directory as the given name. Note that there may be no
69 * directory at all in the given name!
71 * The tmp filename is basically the given filename with a
72 * dot prepended, and .XXXXXX appended (for mkstemp() to
73 * put its unique gunk in). Take care to not exceed
74 * either the MAXPATHLEN or NAME_MAX, esp. the last, as
75 * the basename basically becomes 8 chars longer. In that
76 * case, the original name is shortened sufficiently to
79 * Of course, there's no real reason for the tmp name to
80 * look like the original, except to satisfy us humans.
81 * As long as it's unique, rsync will work.
84 int get_tmpname(char *fnametmp, char *fname)
86 int maxname, added, length = 0;
90 /* Note: this can't overflow, so the return value is safe */
91 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
92 fnametmp[length++] = '/';
95 if ((f = strrchr(fname, '/')) != NULL) {
99 /* copy up to and including the slash */
100 strlcpy(fnametmp, fname, length + 1);
104 fnametmp[length++] = '.';
106 /* The maxname value is bufsize, and includes space for the '\0'.
107 * (Note that NAME_MAX get -8 for the leading '.' above.) */
108 maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
111 rprintf(FERROR, "temporary filename too long: %s\n", fname);
116 added = strlcpy(fnametmp + length, f, maxname);
117 if (added >= maxname)
119 memcpy(fnametmp + length + added, ".XXXXXX", 8);
125 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
126 char *fname, int fd, OFF_T total_size)
128 static char file_sum1[MAX_DIGEST_LEN];
129 static char file_sum2[MAX_DIGEST_LEN];
130 struct map_struct *mapbuf;
131 struct sum_struct sum;
139 read_sum_head(f_in, &sum);
141 if (fd_r >= 0 && size_r > 0) {
142 int32 read_size = MAX(sum.blength * 2, 16*1024);
143 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
145 rprintf(FINFO, "recv mapped %s of size %.0f\n",
146 fname_r, (double)size_r);
151 sum_init(checksum_seed);
153 if (append_mode > 0) {
155 sum.flength = (OFF_T)sum.count * sum.blength;
157 sum.flength -= sum.blength - sum.remainder;
158 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
160 show_progress(offset, total_size);
161 sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
165 if (offset < sum.flength) {
166 int32 len = (int32)(sum.flength - offset);
168 show_progress(offset, total_size);
169 sum_update(map_ptr(mapbuf, offset, len), len);
170 offset = sum.flength;
172 if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) {
173 rsyserr(FERROR, errno, "lseek of %s returned %.0f, not %.0f",
174 full_fname(fname), (double)j, (double)offset);
175 exit_cleanup(RERR_FILEIO);
179 while ((i = recv_token(f_in, &data)) != 0) {
181 show_progress(offset, total_size);
185 rprintf(FINFO,"data recv %d at %.0f\n",
189 stats.literal_data += i;
190 cleanup_got_literal = 1;
194 if (fd != -1 && write_file(fd,data,i) != i)
195 goto report_write_error;
201 offset2 = i * (OFF_T)sum.blength;
203 if (i == (int)sum.count-1 && sum.remainder != 0)
206 stats.matched_data += len;
210 "chunk[%d] of size %ld at %.0f offset=%.0f\n",
211 i, (long)len, (double)offset2, (double)offset);
215 map = map_ptr(mapbuf,offset2,len);
218 sum_update(map, len);
221 if (updating_basis) {
222 if (offset == offset2 && fd != -1) {
224 if (flush_write_file(fd) < 0)
225 goto report_write_error;
227 if ((pos = do_lseek(fd, len, SEEK_CUR)) != offset) {
228 rsyserr(FERROR, errno,
229 "lseek of %s returned %.0f, not %.0f",
231 (double)pos, (double)offset);
232 exit_cleanup(RERR_FILEIO);
237 if (fd != -1 && map && write_file(fd, map, len) != (int)len)
238 goto report_write_error;
242 if (flush_write_file(fd) < 0)
243 goto report_write_error;
245 #ifdef HAVE_FTRUNCATE
246 if (inplace && fd != -1)
247 ftruncate(fd, offset);
251 end_progress(total_size);
253 if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
255 rsyserr(FERROR, errno, "write failed on %s",
257 exit_cleanup(RERR_FILEIO);
260 sum_len = sum_end(file_sum1);
265 read_buf(f_in, file_sum2, sum_len);
267 rprintf(FINFO,"got file_sum\n");
268 if (fd != -1 && memcmp(file_sum1, file_sum2, sum_len) != 0)
274 static void discard_receive_data(int f_in, OFF_T length)
276 receive_data(f_in, NULL, -1, 0, NULL, -1, length);
279 static void handle_delayed_updates(char *local_name)
281 char *fname, *partialptr;
284 for (ndx = -1; (ndx = bitbag_next_bit(delayed_bits, ndx)) >= 0; ) {
285 struct file_struct *file = cur_flist->files[ndx];
286 fname = local_name ? local_name : f_name(file, NULL);
287 if ((partialptr = partial_dir_fname(fname)) != NULL) {
288 if (make_backups > 0 && !make_backup(fname))
291 rprintf(FINFO, "renaming %s to %s\n",
294 /* We don't use robust_rename() here because the
295 * partial-dir must be on the same drive. */
296 if (do_rename(partialptr, fname) < 0) {
297 rsyserr(FERROR, errno,
298 "rename failed for %s (from %s)",
299 full_fname(fname), partialptr);
301 if (remove_source_files
302 || (preserve_hard_links && F_IS_HLINKED(file)))
303 send_msg_int(MSG_SUCCESS, ndx);
304 handle_partial_dir(partialptr, PDIR_DELETE);
310 static int get_next_gen_ndx(int fd, int next_gen_ndx, int desired_ndx)
312 while (next_gen_ndx < desired_ndx) {
313 if (next_gen_ndx >= 0) {
315 "(No batched update for%s \"%s\")\n",
316 redoing ? " resend of" : "",
317 f_name(cur_flist->files[next_gen_ndx], NULL));
319 next_gen_ndx = read_int(fd);
320 if (next_gen_ndx == -1) {
322 next_gen_ndx = first_flist->prev->count + first_flist->prev->ndx_start;
324 next_gen_ndx = cur_flist->count;
331 * main routine for receiver process.
333 * Receiver process runs on the same host as the generator process. */
334 int recv_files(int f_in, char *local_name)
336 int next_gen_ndx = -1;
340 char *fname, fbuf[MAXPATHLEN];
341 char xname[MAXPATHLEN];
342 char fnametmp[MAXPATHLEN];
343 char *fnamecmp, *partialptr;
344 char fnamecmpbuf[MAXPATHLEN];
346 struct file_struct *file;
347 struct stats initial_stats;
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 dflt_perms = (ACCESSPERMS & ~orig_umask);
353 const char *parent_dirname = "";
358 rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->count);
361 delayed_bits = bitbag_create(cur_flist->count + 1);
363 updating_basis = inplace;
368 /* This call also sets cur_flist. */
369 ndx = read_ndx_and_attrs(f_in, -1, &iflags,
370 &fnamecmp_type, xname, &xlen);
371 if (ndx == NDX_DONE) {
372 if (inc_recurse && first_flist) {
373 flist_free(first_flist);
377 if (read_batch && cur_flist) {
378 int high = inc_recurse
379 ? first_flist->prev->count + first_flist->prev->ndx_start
381 get_next_gen_ndx(batch_gen_fd, next_gen_ndx, high);
384 if (++phase > max_phase)
387 rprintf(FINFO, "recv_files phase=%d\n", phase);
388 if (phase == 2 && delay_updates)
389 handle_delayed_updates(local_name);
390 send_msg(MSG_DONE, "", 0);
394 file = cur_flist->files[ndx - cur_flist->ndx_start];
395 fname = local_name ? local_name : f_name(file, fbuf);
398 rprintf(FINFO, "recv_files(%s)\n", fname);
400 if (!(iflags & ITEM_TRANSFER)) {
401 maybe_log_item(file, iflags, itemizing, xname);
406 "got transfer request in phase 2 [%s]\n",
408 exit_cleanup(RERR_PROTOCOL);
411 if (file->flags & FLAG_FILE_SENT) {
412 if (csum_length == SHORT_SUM_LENGTH) {
413 if (keep_partial && !partial_dir)
414 make_backups = -make_backups; /* prevents double backup */
415 append_mode = -append_mode;
416 sparse_files = -sparse_files;
417 csum_length = SUM_LENGTH;
421 if (csum_length != SHORT_SUM_LENGTH) {
422 if (keep_partial && !partial_dir)
423 make_backups = -make_backups;
424 append_mode = -append_mode;
425 sparse_files = -sparse_files;
426 csum_length = SHORT_SUM_LENGTH;
431 stats.current_file_index = ndx;
432 stats.num_transferred_files++;
433 stats.total_transferred_size += F_LENGTH(file);
434 cleanup_got_literal = 0;
436 if (server_filter_list.head
437 && check_filter(&server_filter_list, fname, 0) < 0) {
438 rprintf(FERROR, "attempt to hack rsync failed.\n");
439 exit_cleanup(RERR_PROTOCOL);
442 if (!do_xfers) { /* log the transfer */
443 log_item(FCLIENT, file, &stats, iflags, NULL);
445 discard_receive_data(f_in, F_LENGTH(file));
448 if (write_batch < 0) {
449 log_item(FINFO, file, &stats, iflags, NULL);
451 discard_receive_data(f_in, F_LENGTH(file));
456 next_gen_ndx = get_next_gen_ndx(batch_gen_fd, next_gen_ndx, ndx);
457 if (ndx < next_gen_ndx) {
459 "(Skipping batched update for \"%s\")\n",
461 discard_receive_data(f_in, F_LENGTH(file));
467 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
469 if (protocol_version >= 29) {
470 switch (fnamecmp_type) {
474 case FNAMECMP_PARTIAL_DIR:
475 fnamecmp = partialptr;
477 case FNAMECMP_BACKUP:
478 fnamecmp = get_backup_name(fname);
483 pathjoin(fnamecmpbuf, MAXPATHLEN,
484 file->dirname, xname);
485 fnamecmp = fnamecmpbuf;
491 if (fnamecmp_type >= basis_dir_cnt) {
493 "invalid basis_dir index: %d.\n",
495 exit_cleanup(RERR_PROTOCOL);
497 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
498 basis_dir[fnamecmp_type], fname);
499 fnamecmp = fnamecmpbuf;
502 if (!fnamecmp || (server_filter_list.head
503 && check_filter(&server_filter_list, fname, 0) < 0))
506 /* Reminder: --inplace && --partial-dir are never
507 * enabled at the same time. */
508 if (inplace && make_backups > 0) {
509 if (!(fnamecmp = get_backup_name(fname)))
511 } else if (partial_dir && partialptr)
512 fnamecmp = partialptr;
517 initial_stats = stats;
520 fd1 = do_open(fnamecmp, O_RDONLY, 0);
522 if (fd1 == -1 && protocol_version < 29) {
523 if (fnamecmp != fname) {
525 fd1 = do_open(fnamecmp, O_RDONLY, 0);
528 if (fd1 == -1 && basis_dir[0]) {
529 /* pre-29 allowed only one alternate basis */
530 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
531 basis_dir[0], fname);
532 fnamecmp = fnamecmpbuf;
533 fd1 = do_open(fnamecmp, O_RDONLY, 0);
540 } else if (do_fstat(fd1,&st) != 0) {
541 rsyserr(FERROR, errno, "fstat %s failed",
542 full_fname(fnamecmp));
543 discard_receive_data(f_in, F_LENGTH(file));
548 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
549 /* this special handling for directories
550 * wouldn't be necessary if robust_rename()
551 * and the underlying robust_unlink could cope
554 rprintf(FERROR,"recv_files: %s is a directory\n",
555 full_fname(fnamecmp));
556 discard_receive_data(f_in, F_LENGTH(file));
561 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
566 /* If we're not preserving permissions, change the file-list's
567 * mode based on the local permissions and some heuristics. */
568 if (!preserve_perms) {
569 int exists = fd1 != -1;
571 const char *dn = file->dirname ? file->dirname : ".";
572 if (parent_dirname != dn
573 && strcmp(parent_dirname, dn) != 0) {
574 dflt_perms = default_perms_for_dir(dn);
578 file->mode = dest_mode(file->mode, st.st_mode,
582 /* We now check to see if we are writing the file "inplace" */
584 fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
586 rsyserr(FERROR, errno, "open %s failed",
588 discard_receive_data(f_in, F_LENGTH(file));
594 if (!get_tmpname(fnametmp,fname)) {
595 discard_receive_data(f_in, F_LENGTH(file));
601 /* we initially set the perms without the
602 * setuid/setgid bits to ensure that there is no race
603 * condition. They are then correctly updated after
604 * the lchown. Thanks to snabb@epipe.fi for pointing
605 * this out. We also set it initially without group
606 * access because of a similar race condition. */
607 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
609 /* in most cases parent directories will already exist
610 * because their information should have been previously
611 * transferred, but that may not be the case with -R */
612 if (fd2 == -1 && relative_paths && errno == ENOENT
613 && create_directory_path(fnametmp) == 0) {
614 /* Get back to name with XXXXXX in it. */
615 get_tmpname(fnametmp, fname);
616 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
619 rsyserr(FERROR, errno, "mkstemp %s failed",
620 full_fname(fnametmp));
621 discard_receive_data(f_in, F_LENGTH(file));
627 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
630 /* log the transfer */
631 if (log_before_transfer)
632 log_item(FCLIENT, file, &initial_stats, iflags, NULL);
633 else if (!am_server && verbose && do_progress)
634 rprintf(FINFO, "%s\n", fname);
637 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
638 fname, fd2, F_LENGTH(file));
640 log_item(log_code, file, &initial_stats, iflags, NULL);
644 if (close(fd2) < 0) {
645 rsyserr(FERROR, errno, "close failed on %s",
646 full_fname(fnametmp));
647 exit_cleanup(RERR_FILEIO);
650 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
651 char *temp_copy_name;
652 if (partialptr == fname)
653 partialptr = temp_copy_name = NULL;
654 else if (*partial_dir == '/')
655 temp_copy_name = NULL;
657 temp_copy_name = partialptr;
658 finish_transfer(fname, fnametmp, temp_copy_name,
660 if (fnamecmp == partialptr) {
661 do_unlink(partialptr);
662 handle_partial_dir(partialptr, PDIR_DELETE);
664 } else if (keep_partial && partialptr
665 && handle_partial_dir(partialptr, PDIR_CREATE)) {
666 finish_transfer(partialptr, fnametmp, NULL,
667 file, recv_ok, !partial_dir);
668 if (delay_updates && recv_ok) {
669 bitbag_set_bit(delayed_bits, ndx);
680 if (remove_source_files || inc_recurse
681 || (preserve_hard_links && F_IS_HLINKED(file)))
682 send_msg_int(MSG_SUCCESS, ndx);
683 } else if (!recv_ok) {
684 enum logcode msgtype = redoing || read_batch ? FERROR : FINFO;
685 if (msgtype == FERROR || verbose) {
686 char *errstr, *redostr, *keptstr;
687 if (!(keep_partial && partialptr) && !inplace)
688 keptstr = "discarded";
689 else if (partial_dir)
690 keptstr = "put into partial-dir";
692 keptstr = "retained";
693 if (msgtype == FERROR) {
698 redostr = " (will try again)";
701 "%s: %s failed verification -- update %s%s.\n",
702 errstr, fname, keptstr, redostr);
705 send_msg_int(MSG_REDO, ndx);
706 file->flags |= FLAG_FILE_SENT;
707 } else if (inc_recurse)
708 send_msg_int(MSG_NO_SEND, ndx);
711 if (make_backups < 0)
712 make_backups = -make_backups;
714 if (phase == 2 && delay_updates) /* for protocol_version < 29 */
715 handle_delayed_updates(local_name);
718 rprintf(FINFO,"recv_files finished\n");