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-2008 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 as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
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.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, visit the http://fsf.org website.
27 extern int inc_recurse;
28 extern int log_before_transfer;
29 extern int stdout_format_has_i;
30 extern int logfile_format_has_i;
31 extern int csum_length;
32 extern int read_batch;
33 extern int write_batch;
34 extern int batch_gen_fd;
35 extern int protocol_version;
36 extern int relative_paths;
37 extern int preserve_hard_links;
38 extern int preserve_perms;
39 extern int preserve_xattrs;
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_len;
48 extern int checksum_seed;
50 extern int delay_updates;
51 extern mode_t orig_umask;
52 extern struct stats stats;
54 extern char *partial_dir;
55 extern char *basis_dir[MAX_BASIS_DIRS+1];
56 extern char sender_file_sum[MAX_DIGEST_LEN];
57 extern struct file_list *cur_flist, *first_flist, *dir_flist;
58 extern struct filter_list_struct daemon_filter_list;
60 static struct bitbag *delayed_bits = NULL;
61 static int phase = 0, redoing = 0;
62 /* We're either updating the basis file or an identical copy: */
63 static int updating_basis_or_equiv;
66 * get_tmpname() - create a tmp filename for a given filename
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!
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
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.
86 int get_tmpname(char *fnametmp, const char *fname)
88 int maxname, added, length = 0;
92 /* Note: this can't overflow, so the return value is safe */
93 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
94 fnametmp[length++] = '/';
97 if ((f = strrchr(fname, '/')) != NULL) {
101 /* copy up to and including the slash */
102 strlcpy(fnametmp, fname, length + 1);
106 fnametmp[length++] = '.';
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);
113 rprintf(FERROR_XFER, "temporary filename too long: %s\n", fname);
118 added = strlcpy(fnametmp + length, f, maxname);
119 if (added >= maxname)
121 memcpy(fnametmp + length + added, ".XXXXXX", 8);
126 /* Opens a temporary file for writing.
127 * Success: Writes name into fnametmp, returns fd.
128 * Failure: Clobbers fnametmp, returns -1.
129 * Calling cleanup_set() is the caller's job. */
130 int open_tmpfile(char *fnametmp, const char *fname, struct file_struct *file)
134 if (!get_tmpname(fnametmp, fname))
137 /* We initially set the perms without the setuid/setgid bits or group
138 * access to ensure that there is no race condition. They will be
139 * correctly updated after the right owner and group info is set.
140 * (Thanks to snabb@epipe.fi for pointing this out.) */
141 fd = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
144 /* In most cases parent directories will already exist because their
145 * information should have been previously transferred, but that may
146 * not be the case with -R */
147 if (fd == -1 && relative_paths && errno == ENOENT
148 && create_directory_path(fnametmp) == 0) {
149 /* Get back to name with XXXXXX in it. */
150 get_tmpname(fnametmp, fname);
151 fd = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
156 rsyserr(FERROR_XFER, errno, "mkstemp %s failed",
157 full_fname(fnametmp));
164 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
165 const char *fname, int fd, OFF_T total_size)
167 static char file_sum1[MAX_DIGEST_LEN];
168 struct map_struct *mapbuf;
169 struct sum_struct sum;
177 read_sum_head(f_in, &sum);
179 if (fd_r >= 0 && size_r > 0) {
180 int32 read_size = MAX(sum.blength * 2, 16*1024);
181 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
182 if (DEBUG_GTE(DELTASUM, 2)) {
183 rprintf(FINFO, "recv mapped %s of size %s\n",
184 fname_r, big_num(size_r, 0));
189 sum_init(checksum_seed);
191 if (append_mode > 0) {
193 sum.flength = (OFF_T)sum.count * sum.blength;
195 sum.flength -= sum.blength - sum.remainder;
196 if (append_mode == 2) {
197 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
198 if (INFO_GTE(PROGRESS, 1))
199 show_progress(offset, total_size);
200 sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
204 if (offset < sum.flength) {
205 int32 len = (int32)(sum.flength - offset);
206 if (INFO_GTE(PROGRESS, 1))
207 show_progress(offset, total_size);
208 sum_update(map_ptr(mapbuf, offset, len), len);
211 offset = sum.flength;
212 if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) {
213 rsyserr(FERROR_XFER, errno, "lseek of %s returned %s, not %s",
214 full_fname(fname), big_num(j, 0), big_num(offset, 0));
215 exit_cleanup(RERR_FILEIO);
219 while ((i = recv_token(f_in, &data)) != 0) {
220 if (INFO_GTE(PROGRESS, 1))
221 show_progress(offset, total_size);
224 if (DEBUG_GTE(DELTASUM, 3)) {
225 rprintf(FINFO,"data recv %d at %s\n",
226 i, big_num(offset, 0));
229 stats.literal_data += i;
230 cleanup_got_literal = 1;
234 if (fd != -1 && write_file(fd,data,i) != i)
235 goto report_write_error;
241 offset2 = i * (OFF_T)sum.blength;
243 if (i == (int)sum.count-1 && sum.remainder != 0)
246 stats.matched_data += len;
248 if (DEBUG_GTE(DELTASUM, 3)) {
250 "chunk[%d] of size %ld at %s offset=%s\n",
251 i, (long)len, big_num(offset2, 0), big_num(offset, 0));
255 map = map_ptr(mapbuf,offset2,len);
258 sum_update(map, len);
261 if (updating_basis_or_equiv) {
262 if (offset == offset2 && fd != -1) {
264 if (flush_write_file(fd) < 0)
265 goto report_write_error;
267 if ((pos = do_lseek(fd, len, SEEK_CUR)) != offset) {
268 rsyserr(FERROR_XFER, errno,
269 "lseek of %s returned %s, not %s",
271 big_num(pos, 0), big_num(offset, 0));
272 exit_cleanup(RERR_FILEIO);
277 if (fd != -1 && map && write_file(fd, map, len) != (int)len)
278 goto report_write_error;
282 if (flush_write_file(fd) < 0)
283 goto report_write_error;
285 #ifdef HAVE_FTRUNCATE
286 if (inplace && fd != -1)
287 ftruncate(fd, offset);
290 if (INFO_GTE(PROGRESS, 1))
291 end_progress(total_size);
293 if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
295 rsyserr(FERROR_XFER, errno, "write failed on %s",
297 exit_cleanup(RERR_FILEIO);
300 if (sum_end(file_sum1) != checksum_len)
301 overflow_exit("checksum_len"); /* Impossible... */
306 read_buf(f_in, sender_file_sum, checksum_len);
307 if (DEBUG_GTE(DELTASUM, 2))
308 rprintf(FINFO,"got file_sum\n");
309 if (fd != -1 && memcmp(file_sum1, sender_file_sum, checksum_len) != 0)
315 static void discard_receive_data(int f_in, OFF_T length)
317 receive_data(f_in, NULL, -1, 0, NULL, -1, length);
320 static void handle_delayed_updates(char *local_name)
322 char *fname, *partialptr;
325 for (ndx = -1; (ndx = bitbag_next_bit(delayed_bits, ndx)) >= 0; ) {
326 struct file_struct *file = cur_flist->files[ndx];
327 fname = local_name ? local_name : f_name(file, NULL);
328 if ((partialptr = partial_dir_fname(fname)) != NULL) {
329 if (make_backups > 0 && !make_backup(fname))
331 if (DEBUG_GTE(RECV, 1)) {
332 rprintf(FINFO, "renaming %s to %s\n",
335 /* We don't use robust_rename() here because the
336 * partial-dir must be on the same drive. */
337 if (do_rename(partialptr, fname) < 0) {
338 rsyserr(FERROR_XFER, errno,
339 "rename failed for %s (from %s)",
340 full_fname(fname), partialptr);
342 if (remove_source_files
343 || (preserve_hard_links && F_IS_HLINKED(file)))
344 send_msg_int(MSG_SUCCESS, ndx);
345 handle_partial_dir(partialptr, PDIR_DELETE);
351 static int get_next_gen_ndx(int fd, int next_gen_ndx, int desired_ndx)
353 while (next_gen_ndx < desired_ndx) {
354 if (next_gen_ndx >= 0) {
355 struct file_struct *file = cur_flist->files[next_gen_ndx];
357 "(No batched update for%s \"%s\")\n",
358 file->flags & FLAG_FILE_SENT ? " resend of" : "",
361 next_gen_ndx = read_int(fd);
362 if (next_gen_ndx == -1) {
364 next_gen_ndx = first_flist->prev->used + first_flist->prev->ndx_start;
366 next_gen_ndx = cur_flist->used;
373 * main routine for receiver process.
375 * Receiver process runs on the same host as the generator process. */
376 int recv_files(int f_in, char *local_name)
378 int next_gen_ndx = -1;
382 char *fname, fbuf[MAXPATHLEN];
383 char xname[MAXPATHLEN];
384 char fnametmp[MAXPATHLEN];
385 char *fnamecmp, *partialptr;
386 char fnamecmpbuf[MAXPATHLEN];
388 struct file_struct *file;
389 struct stats initial_stats;
390 int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
391 enum logcode log_code = log_before_transfer ? FLOG : FINFO;
392 int max_phase = protocol_version >= 29 ? 2 : 1;
393 int dflt_perms = (ACCESSPERMS & ~orig_umask);
395 const char *parent_dirname = "";
399 if (DEBUG_GTE(RECV, 1))
400 rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used);
403 delayed_bits = bitbag_create(cur_flist->used + 1);
408 /* This call also sets cur_flist. */
409 ndx = read_ndx_and_attrs(f_in, &iflags, &fnamecmp_type,
411 if (ndx == NDX_DONE) {
412 if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) {
413 set_current_file_index(NULL, 0);
416 if (inc_recurse && first_flist) {
417 flist_free(first_flist);
421 if (read_batch && cur_flist) {
422 int high = inc_recurse
423 ? first_flist->prev->used + first_flist->prev->ndx_start
425 get_next_gen_ndx(batch_gen_fd, next_gen_ndx, high);
428 if (++phase > max_phase)
430 if (DEBUG_GTE(RECV, 1))
431 rprintf(FINFO, "recv_files phase=%d\n", phase);
432 if (phase == 2 && delay_updates)
433 handle_delayed_updates(local_name);
434 send_msg(MSG_DONE, "", 0, 0);
438 if (ndx - cur_flist->ndx_start >= 0)
439 file = cur_flist->files[ndx - cur_flist->ndx_start];
441 file = dir_flist->files[cur_flist->parent_ndx];
442 fname = local_name ? local_name : f_name(file, fbuf);
444 if (DEBUG_GTE(RECV, 1))
445 rprintf(FINFO, "recv_files(%s)\n", fname);
447 #ifdef SUPPORT_XATTRS
448 if (iflags & ITEM_REPORT_XATTR && !dry_run)
449 recv_xattr_request(file, f_in);
452 if (!(iflags & ITEM_TRANSFER)) {
453 maybe_log_item(file, iflags, itemizing, xname);
454 #ifdef SUPPORT_XATTRS
455 if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && !dry_run)
456 set_file_attrs(fname, file, NULL, fname, 0);
462 "got transfer request in phase 2 [%s]\n",
464 exit_cleanup(RERR_PROTOCOL);
467 if (file->flags & FLAG_FILE_SENT) {
468 if (csum_length == SHORT_SUM_LENGTH) {
469 if (keep_partial && !partial_dir)
470 make_backups = -make_backups; /* prevents double backup */
472 sparse_files = -sparse_files;
473 append_mode = -append_mode;
474 csum_length = SUM_LENGTH;
478 if (csum_length != SHORT_SUM_LENGTH) {
479 if (keep_partial && !partial_dir)
480 make_backups = -make_backups;
482 sparse_files = -sparse_files;
483 append_mode = -append_mode;
484 csum_length = SHORT_SUM_LENGTH;
489 if (!am_server && INFO_GTE(PROGRESS, 1))
490 set_current_file_index(file, ndx);
491 stats.num_transferred_files++;
492 stats.total_transferred_size += F_LENGTH(file);
494 cleanup_got_literal = 0;
496 if (daemon_filter_list.head
497 && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) {
498 rprintf(FERROR, "attempt to hack rsync failed.\n");
499 exit_cleanup(RERR_PROTOCOL);
502 if (!do_xfers) { /* log the transfer */
503 log_item(FCLIENT, file, &stats, iflags, NULL);
505 discard_receive_data(f_in, F_LENGTH(file));
508 if (write_batch < 0) {
509 log_item(FCLIENT, file, &stats, iflags, NULL);
511 discard_receive_data(f_in, F_LENGTH(file));
516 next_gen_ndx = get_next_gen_ndx(batch_gen_fd, next_gen_ndx, ndx);
517 if (ndx < next_gen_ndx) {
519 "(Skipping batched update for \"%s\")\n",
521 discard_receive_data(f_in, F_LENGTH(file));
523 send_msg_int(MSG_NO_SEND, ndx);
529 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
531 if (protocol_version >= 29) {
532 switch (fnamecmp_type) {
536 case FNAMECMP_PARTIAL_DIR:
537 fnamecmp = partialptr;
539 case FNAMECMP_BACKUP:
540 fnamecmp = get_backup_name(fname);
544 pathjoin(fnamecmpbuf, MAXPATHLEN,
545 file->dirname, xname);
546 fnamecmp = fnamecmpbuf;
551 if (fnamecmp_type >= basis_dir_cnt) {
553 "invalid basis_dir index: %d.\n",
555 exit_cleanup(RERR_PROTOCOL);
557 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
558 basis_dir[fnamecmp_type], fname);
559 fnamecmp = fnamecmpbuf;
562 if (!fnamecmp || (daemon_filter_list.head
563 && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) {
565 fnamecmp_type = FNAMECMP_FNAME;
568 /* Reminder: --inplace && --partial-dir are never
569 * enabled at the same time. */
570 if (inplace && make_backups > 0) {
571 if (!(fnamecmp = get_backup_name(fname)))
574 fnamecmp_type = FNAMECMP_BACKUP;
575 } else if (partial_dir && partialptr)
576 fnamecmp = partialptr;
581 initial_stats = stats;
584 fd1 = do_open(fnamecmp, O_RDONLY, 0);
586 if (fd1 == -1 && protocol_version < 29) {
587 if (fnamecmp != fname) {
589 fd1 = do_open(fnamecmp, O_RDONLY, 0);
592 if (fd1 == -1 && basis_dir[0]) {
593 /* pre-29 allowed only one alternate basis */
594 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
595 basis_dir[0], fname);
596 fnamecmp = fnamecmpbuf;
597 fd1 = do_open(fnamecmp, O_RDONLY, 0);
601 updating_basis_or_equiv = inplace
602 && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP);
607 } else if (do_fstat(fd1,&st) != 0) {
608 rsyserr(FERROR_XFER, errno, "fstat %s failed",
609 full_fname(fnamecmp));
610 discard_receive_data(f_in, F_LENGTH(file));
613 send_msg_int(MSG_NO_SEND, ndx);
617 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
618 /* this special handling for directories
619 * wouldn't be necessary if robust_rename()
620 * and the underlying robust_unlink could cope
623 rprintf(FERROR_XFER, "recv_files: %s is a directory\n",
624 full_fname(fnamecmp));
625 discard_receive_data(f_in, F_LENGTH(file));
628 send_msg_int(MSG_NO_SEND, ndx);
632 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
637 /* If we're not preserving permissions, change the file-list's
638 * mode based on the local permissions and some heuristics. */
639 if (!preserve_perms) {
640 int exists = fd1 != -1;
642 const char *dn = file->dirname ? file->dirname : ".";
643 if (parent_dirname != dn
644 && strcmp(parent_dirname, dn) != 0) {
645 dflt_perms = default_perms_for_dir(dn);
649 file->mode = dest_mode(file->mode, st.st_mode,
653 /* We now check to see if we are writing the file "inplace" */
655 fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
657 rsyserr(FERROR_XFER, errno, "open %s failed",
661 fd2 = open_tmpfile(fnametmp, fname, file);
663 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
667 discard_receive_data(f_in, F_LENGTH(file));
671 send_msg_int(MSG_NO_SEND, ndx);
675 /* log the transfer */
676 if (log_before_transfer)
677 log_item(FCLIENT, file, &initial_stats, iflags, NULL);
678 else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))
679 rprintf(FINFO, "%s\n", fname);
682 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
683 fname, fd2, F_LENGTH(file));
685 log_item(log_code, file, &initial_stats, iflags, NULL);
689 if (close(fd2) < 0) {
690 rsyserr(FERROR, errno, "close failed on %s",
691 full_fname(fnametmp));
692 exit_cleanup(RERR_FILEIO);
695 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
696 if (partialptr == fname)
698 if (!finish_transfer(fname, fnametmp, fnamecmp,
699 partialptr, file, recv_ok, 1))
701 else if (fnamecmp == partialptr) {
702 do_unlink(partialptr);
703 handle_partial_dir(partialptr, PDIR_DELETE);
705 } else if (keep_partial && partialptr
706 && handle_partial_dir(partialptr, PDIR_CREATE)) {
707 if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,
708 file, recv_ok, !partial_dir))
710 else if (delay_updates && recv_ok) {
711 bitbag_set_bit(delayed_bits, ndx);
723 if (remove_source_files || inc_recurse
724 || (preserve_hard_links && F_IS_HLINKED(file)))
725 send_msg_int(MSG_SUCCESS, ndx);
728 enum logcode msgtype = redoing ? FERROR_XFER : FWARNING;
729 if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) {
730 char *errstr, *redostr, *keptstr;
731 if (!(keep_partial && partialptr) && !inplace)
732 keptstr = "discarded";
733 else if (partial_dir)
734 keptstr = "put into partial-dir";
736 keptstr = "retained";
737 if (msgtype == FERROR_XFER) {
742 redostr = read_batch ? " (may try again)"
743 : " (will try again)";
746 "%s: %s failed verification -- update %s%s.\n",
747 errstr, local_name ? f_name(file, NULL) : fname,
751 send_msg_int(MSG_REDO, ndx);
752 file->flags |= FLAG_FILE_SENT;
753 } else if (inc_recurse)
754 send_msg_int(MSG_NO_SEND, ndx);
759 send_msg_int(MSG_NO_SEND, ndx);
763 if (make_backups < 0)
764 make_backups = -make_backups;
766 if (phase == 2 && delay_updates) /* for protocol_version < 29 */
767 handle_delayed_updates(local_name);
769 if (DEBUG_GTE(RECV, 1))
770 rprintf(FINFO,"recv_files finished\n");