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_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, *dir_flist;
56 extern struct filter_list_struct daemon_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_or_equiv;
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, const 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_XFER, "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);
124 /* Opens a temporary file for writing.
125 * Success: Writes name into fnametmp, returns fd.
126 * Failure: Clobbers fnametmp, returns -1.
127 * Calling cleanup_set() is the caller's job. */
128 int open_tmpfile(char *fnametmp, const char *fname, struct file_struct *file)
132 if (!get_tmpname(fnametmp, fname))
135 /* We initially set the perms without the setuid/setgid bits or group
136 * access to ensure that there is no race condition. They will be
137 * correctly updated after the right owner and group info is set.
138 * (Thanks to snabb@epipe.fi for pointing this out.) */
139 fd = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
142 /* In most cases parent directories will already exist because their
143 * information should have been previously transferred, but that may
144 * not be the case with -R */
145 if (fd == -1 && relative_paths && errno == ENOENT
146 && create_directory_path(fnametmp) == 0) {
147 /* Get back to name with XXXXXX in it. */
148 get_tmpname(fnametmp, fname);
149 fd = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
154 rsyserr(FERROR_XFER, errno, "mkstemp %s failed",
155 full_fname(fnametmp));
162 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
163 const char *fname, int fd, OFF_T total_size)
165 static char file_sum1[MAX_DIGEST_LEN];
166 static char file_sum2[MAX_DIGEST_LEN];
167 struct map_struct *mapbuf;
168 struct sum_struct sum;
176 read_sum_head(f_in, &sum);
178 if (fd_r >= 0 && size_r > 0) {
179 int32 read_size = MAX(sum.blength * 2, 16*1024);
180 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
181 if (DEBUG_GTE(CHKSUM, 2)) {
182 rprintf(FINFO, "recv mapped %s of size %s\n",
183 fname_r, big_num(size_r, 0));
188 sum_init(checksum_seed);
190 if (append_mode > 0) {
192 sum.flength = (OFF_T)sum.count * sum.blength;
194 sum.flength -= sum.blength - sum.remainder;
195 if (append_mode == 2) {
196 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
197 if (INFO_GTE(PROGRESS, 1))
198 show_progress(offset, total_size);
199 sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
203 if (offset < sum.flength) {
204 int32 len = (int32)(sum.flength - offset);
205 if (INFO_GTE(PROGRESS, 1))
206 show_progress(offset, total_size);
207 sum_update(map_ptr(mapbuf, offset, len), len);
210 offset = sum.flength;
211 if (fd != -1 && (j = do_lseek(fd, offset, SEEK_SET)) != offset) {
212 rsyserr(FERROR_XFER, errno, "lseek of %s returned %s, not %s",
213 full_fname(fname), big_num(j, 0), big_num(offset, 0));
214 exit_cleanup(RERR_FILEIO);
218 while ((i = recv_token(f_in, &data)) != 0) {
219 if (INFO_GTE(PROGRESS, 1))
220 show_progress(offset, total_size);
223 if (DEBUG_GTE(CHKSUM, 3)) {
224 rprintf(FINFO,"data recv %d at %s\n",
225 i, big_num(offset, 0));
228 stats.literal_data += i;
229 cleanup_got_literal = 1;
233 if (fd != -1 && write_file(fd,data,i) != i)
234 goto report_write_error;
240 offset2 = i * (OFF_T)sum.blength;
242 if (i == (int)sum.count-1 && sum.remainder != 0)
245 stats.matched_data += len;
247 if (DEBUG_GTE(CHKSUM, 3)) {
249 "chunk[%d] of size %ld at %s offset=%s\n",
250 i, (long)len, big_num(offset2, 0), big_num(offset, 0));
254 map = map_ptr(mapbuf,offset2,len);
257 sum_update(map, len);
260 if (updating_basis_or_equiv) {
261 if (offset == offset2 && fd != -1) {
263 if (flush_write_file(fd) < 0)
264 goto report_write_error;
266 if ((pos = do_lseek(fd, len, SEEK_CUR)) != offset) {
267 rsyserr(FERROR_XFER, errno,
268 "lseek of %s returned %s, not %s",
270 big_num(pos, 0), big_num(offset, 0));
271 exit_cleanup(RERR_FILEIO);
276 if (fd != -1 && map && write_file(fd, map, len) != (int)len)
277 goto report_write_error;
281 if (flush_write_file(fd) < 0)
282 goto report_write_error;
284 #ifdef HAVE_FTRUNCATE
285 if (inplace && fd != -1)
286 ftruncate(fd, offset);
289 if (INFO_GTE(PROGRESS, 1))
290 end_progress(total_size);
292 if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
294 rsyserr(FERROR_XFER, errno, "write failed on %s",
296 exit_cleanup(RERR_FILEIO);
299 sum_len = sum_end(file_sum1);
304 read_buf(f_in, file_sum2, sum_len);
305 if (DEBUG_GTE(CHKSUM, 2))
306 rprintf(FINFO,"got file_sum\n");
307 if (fd != -1 && memcmp(file_sum1, file_sum2, sum_len) != 0)
313 static void discard_receive_data(int f_in, OFF_T length)
315 receive_data(f_in, NULL, -1, 0, NULL, -1, length);
318 static void handle_delayed_updates(char *local_name)
320 char *fname, *partialptr;
323 for (ndx = -1; (ndx = bitbag_next_bit(delayed_bits, ndx)) >= 0; ) {
324 struct file_struct *file = cur_flist->files[ndx];
325 fname = local_name ? local_name : f_name(file, NULL);
326 if ((partialptr = partial_dir_fname(fname)) != NULL) {
327 if (make_backups > 0 && !make_backup(fname))
329 if (DEBUG_GTE(RECV, 1)) {
330 rprintf(FINFO, "renaming %s to %s\n",
333 /* We don't use robust_rename() here because the
334 * partial-dir must be on the same drive. */
335 if (do_rename(partialptr, fname) < 0) {
336 rsyserr(FERROR_XFER, errno,
337 "rename failed for %s (from %s)",
338 full_fname(fname), partialptr);
340 if (remove_source_files
341 || (preserve_hard_links && F_IS_HLINKED(file)))
342 send_msg_int(MSG_SUCCESS, ndx);
343 handle_partial_dir(partialptr, PDIR_DELETE);
349 static int get_next_gen_ndx(int fd, int next_gen_ndx, int desired_ndx)
351 while (next_gen_ndx < desired_ndx) {
352 if (next_gen_ndx >= 0) {
353 struct file_struct *file = cur_flist->files[next_gen_ndx];
355 "(No batched update for%s \"%s\")\n",
356 file->flags & FLAG_FILE_SENT ? " resend of" : "",
359 next_gen_ndx = read_int(fd);
360 if (next_gen_ndx == -1) {
362 next_gen_ndx = first_flist->prev->used + first_flist->prev->ndx_start;
364 next_gen_ndx = cur_flist->used;
371 * main routine for receiver process.
373 * Receiver process runs on the same host as the generator process. */
374 int recv_files(int f_in, char *local_name)
376 int next_gen_ndx = -1;
380 char *fname, fbuf[MAXPATHLEN];
381 char xname[MAXPATHLEN];
382 char fnametmp[MAXPATHLEN];
383 char *fnamecmp, *partialptr;
384 char fnamecmpbuf[MAXPATHLEN];
386 struct file_struct *file;
387 struct stats initial_stats;
388 int itemizing = am_server ? logfile_format_has_i : stdout_format_has_i;
389 enum logcode log_code = log_before_transfer ? FLOG : FINFO;
390 int max_phase = protocol_version >= 29 ? 2 : 1;
391 int dflt_perms = (ACCESSPERMS & ~orig_umask);
393 const char *parent_dirname = "";
397 if (DEBUG_GTE(RECV, 1))
398 rprintf(FINFO, "recv_files(%d) starting\n", cur_flist->used);
401 delayed_bits = bitbag_create(cur_flist->used + 1);
406 /* This call also sets cur_flist. */
407 ndx = read_ndx_and_attrs(f_in, &iflags, &fnamecmp_type,
409 if (ndx == NDX_DONE) {
410 if (!am_server && INFO_GTE(PROGRESS, 2) && cur_flist) {
411 set_current_file_index(NULL, 0);
414 if (inc_recurse && first_flist) {
415 flist_free(first_flist);
419 if (read_batch && cur_flist) {
420 int high = inc_recurse
421 ? first_flist->prev->used + first_flist->prev->ndx_start
423 get_next_gen_ndx(batch_gen_fd, next_gen_ndx, high);
426 if (++phase > max_phase)
428 if (DEBUG_GTE(RECV, 1))
429 rprintf(FINFO, "recv_files phase=%d\n", phase);
430 if (phase == 2 && delay_updates)
431 handle_delayed_updates(local_name);
432 send_msg(MSG_DONE, "", 0, 0);
436 if (ndx - cur_flist->ndx_start >= 0)
437 file = cur_flist->files[ndx - cur_flist->ndx_start];
439 file = dir_flist->files[cur_flist->parent_ndx];
440 fname = local_name ? local_name : f_name(file, fbuf);
442 if (DEBUG_GTE(RECV, 1))
443 rprintf(FINFO, "recv_files(%s)\n", fname);
445 #ifdef SUPPORT_XATTRS
446 if (iflags & ITEM_REPORT_XATTR && !dry_run)
447 recv_xattr_request(file, f_in);
450 if (!(iflags & ITEM_TRANSFER)) {
451 maybe_log_item(file, iflags, itemizing, xname);
452 #ifdef SUPPORT_XATTRS
453 if (preserve_xattrs && iflags & ITEM_REPORT_XATTR && !dry_run)
454 set_file_attrs(fname, file, NULL, fname, 0);
460 "got transfer request in phase 2 [%s]\n",
462 exit_cleanup(RERR_PROTOCOL);
465 if (file->flags & FLAG_FILE_SENT) {
466 if (csum_length == SHORT_SUM_LENGTH) {
467 if (keep_partial && !partial_dir)
468 make_backups = -make_backups; /* prevents double backup */
470 sparse_files = -sparse_files;
471 append_mode = -append_mode;
472 csum_length = SUM_LENGTH;
476 if (csum_length != SHORT_SUM_LENGTH) {
477 if (keep_partial && !partial_dir)
478 make_backups = -make_backups;
480 sparse_files = -sparse_files;
481 append_mode = -append_mode;
482 csum_length = SHORT_SUM_LENGTH;
487 if (!am_server && INFO_GTE(PROGRESS, 1))
488 set_current_file_index(file, ndx);
489 stats.num_transferred_files++;
490 stats.total_transferred_size += F_LENGTH(file);
492 cleanup_got_literal = 0;
494 if (daemon_filter_list.head
495 && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0) {
496 rprintf(FERROR, "attempt to hack rsync failed.\n");
497 exit_cleanup(RERR_PROTOCOL);
500 if (!do_xfers) { /* log the transfer */
501 log_item(FCLIENT, file, &stats, iflags, NULL);
503 discard_receive_data(f_in, F_LENGTH(file));
506 if (write_batch < 0) {
507 log_item(FCLIENT, file, &stats, iflags, NULL);
509 discard_receive_data(f_in, F_LENGTH(file));
514 next_gen_ndx = get_next_gen_ndx(batch_gen_fd, next_gen_ndx, ndx);
515 if (ndx < next_gen_ndx) {
517 "(Skipping batched update for \"%s\")\n",
519 discard_receive_data(f_in, F_LENGTH(file));
521 send_msg_int(MSG_NO_SEND, ndx);
527 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
529 if (protocol_version >= 29) {
530 switch (fnamecmp_type) {
534 case FNAMECMP_PARTIAL_DIR:
535 fnamecmp = partialptr;
537 case FNAMECMP_BACKUP:
538 fnamecmp = get_backup_name(fname);
542 pathjoin(fnamecmpbuf, MAXPATHLEN,
543 file->dirname, xname);
544 fnamecmp = fnamecmpbuf;
549 if (fnamecmp_type >= basis_dir_cnt) {
551 "invalid basis_dir index: %d.\n",
553 exit_cleanup(RERR_PROTOCOL);
555 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
556 basis_dir[fnamecmp_type], fname);
557 fnamecmp = fnamecmpbuf;
560 if (!fnamecmp || (daemon_filter_list.head
561 && check_filter(&daemon_filter_list, FLOG, fname, 0) < 0)) {
563 fnamecmp_type = FNAMECMP_FNAME;
566 /* Reminder: --inplace && --partial-dir are never
567 * enabled at the same time. */
568 if (inplace && make_backups > 0) {
569 if (!(fnamecmp = get_backup_name(fname)))
572 fnamecmp_type = FNAMECMP_BACKUP;
573 } else if (partial_dir && partialptr)
574 fnamecmp = partialptr;
579 initial_stats = stats;
582 fd1 = do_open(fnamecmp, O_RDONLY, 0);
584 if (fd1 == -1 && protocol_version < 29) {
585 if (fnamecmp != fname) {
587 fd1 = do_open(fnamecmp, O_RDONLY, 0);
590 if (fd1 == -1 && basis_dir[0]) {
591 /* pre-29 allowed only one alternate basis */
592 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
593 basis_dir[0], fname);
594 fnamecmp = fnamecmpbuf;
595 fd1 = do_open(fnamecmp, O_RDONLY, 0);
599 updating_basis_or_equiv = inplace
600 && (fnamecmp == fname || fnamecmp_type == FNAMECMP_BACKUP);
605 } else if (do_fstat(fd1,&st) != 0) {
606 rsyserr(FERROR_XFER, errno, "fstat %s failed",
607 full_fname(fnamecmp));
608 discard_receive_data(f_in, F_LENGTH(file));
611 send_msg_int(MSG_NO_SEND, ndx);
615 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
616 /* this special handling for directories
617 * wouldn't be necessary if robust_rename()
618 * and the underlying robust_unlink could cope
621 rprintf(FERROR_XFER, "recv_files: %s is a directory\n",
622 full_fname(fnamecmp));
623 discard_receive_data(f_in, F_LENGTH(file));
626 send_msg_int(MSG_NO_SEND, ndx);
630 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
635 /* If we're not preserving permissions, change the file-list's
636 * mode based on the local permissions and some heuristics. */
637 if (!preserve_perms) {
638 int exists = fd1 != -1;
640 const char *dn = file->dirname ? file->dirname : ".";
641 if (parent_dirname != dn
642 && strcmp(parent_dirname, dn) != 0) {
643 dflt_perms = default_perms_for_dir(dn);
647 file->mode = dest_mode(file->mode, st.st_mode,
651 /* We now check to see if we are writing the file "inplace" */
653 fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
655 rsyserr(FERROR_XFER, errno, "open %s failed",
659 fd2 = open_tmpfile(fnametmp, fname, file);
661 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
665 discard_receive_data(f_in, F_LENGTH(file));
669 send_msg_int(MSG_NO_SEND, ndx);
673 /* log the transfer */
674 if (log_before_transfer)
675 log_item(FCLIENT, file, &initial_stats, iflags, NULL);
676 else if (!am_server && INFO_GTE(NAME, 1) && INFO_EQ(PROGRESS, 1))
677 rprintf(FINFO, "%s\n", fname);
680 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
681 fname, fd2, F_LENGTH(file));
683 log_item(log_code, file, &initial_stats, iflags, NULL);
687 if (close(fd2) < 0) {
688 rsyserr(FERROR, errno, "close failed on %s",
689 full_fname(fnametmp));
690 exit_cleanup(RERR_FILEIO);
693 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
694 if (partialptr == fname)
696 if (!finish_transfer(fname, fnametmp, fnamecmp,
697 partialptr, file, recv_ok, 1))
699 else if (fnamecmp == partialptr) {
700 do_unlink(partialptr);
701 handle_partial_dir(partialptr, PDIR_DELETE);
703 } else if (keep_partial && partialptr
704 && handle_partial_dir(partialptr, PDIR_CREATE)) {
705 if (!finish_transfer(partialptr, fnametmp, fnamecmp, NULL,
706 file, recv_ok, !partial_dir))
708 else if (delay_updates && recv_ok) {
709 bitbag_set_bit(delayed_bits, ndx);
721 if (remove_source_files || inc_recurse
722 || (preserve_hard_links && F_IS_HLINKED(file)))
723 send_msg_int(MSG_SUCCESS, ndx);
726 enum logcode msgtype = redoing ? FERROR_XFER : FWARNING;
727 if (msgtype == FERROR_XFER || INFO_GTE(NAME, 1)) {
728 char *errstr, *redostr, *keptstr;
729 if (!(keep_partial && partialptr) && !inplace)
730 keptstr = "discarded";
731 else if (partial_dir)
732 keptstr = "put into partial-dir";
734 keptstr = "retained";
735 if (msgtype == FERROR_XFER) {
740 redostr = read_batch ? " (may try again)"
741 : " (will try again)";
744 "%s: %s failed verification -- update %s%s.\n",
745 errstr, local_name ? f_name(file, NULL) : fname,
749 send_msg_int(MSG_REDO, ndx);
750 file->flags |= FLAG_FILE_SENT;
751 } else if (inc_recurse)
752 send_msg_int(MSG_NO_SEND, ndx);
757 send_msg_int(MSG_NO_SEND, ndx);
761 if (make_backups < 0)
762 make_backups = -make_backups;
764 if (phase == 2 && delay_updates) /* for protocol_version < 29 */
765 handle_delayed_updates(local_name);
767 if (DEBUG_GTE(RECV, 1))
768 rprintf(FINFO,"recv_files finished\n");