Got rid of kluged value for am_sender, and instead added a new
[rsync/rsync.git] / receiver.c
... / ...
CommitLineData
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
23extern int verbose;
24extern int dry_run;
25extern int am_daemon;
26extern int am_server;
27extern int do_progress;
28extern int log_before_transfer;
29extern int log_format_has_i;
30extern int daemon_log_format_has_i;
31extern int delete_after;
32extern int csum_length;
33extern int read_batch;
34extern int batch_gen_fd;
35extern int protocol_version;
36extern int relative_paths;
37extern int keep_dirlinks;
38extern int preserve_hard_links;
39extern int preserve_perms;
40extern int io_error;
41extern int basis_dir_cnt;
42extern int make_backups;
43extern int cleanup_got_literal;
44extern int remove_sent_files;
45extern int module_id;
46extern int ignore_errors;
47extern int orig_umask;
48extern int keep_partial;
49extern int checksum_seed;
50extern int inplace;
51extern int delay_updates;
52extern struct stats stats;
53extern char *log_format;
54extern char *tmpdir;
55extern char *partial_dir;
56extern char *basis_dir[];
57
58extern struct filter_list_struct server_filter_list;
59
60
61/* This deletes any files on the receiving side that are not present on the
62 * sending side. This is used by --delete-before and --delete-after. */
63void delete_files(struct file_list *flist)
64{
65 char fbuf[MAXPATHLEN];
66 int j;
67
68 for (j = 0; j < flist->count; j++) {
69 struct file_struct *file = flist->files[j];
70
71 if (!(file->flags & FLAG_DEL_HERE))
72 continue;
73
74 f_name_to(file, fbuf);
75 if (verbose > 1 && file->flags & FLAG_TOP_DIR)
76 rprintf(FINFO, "deleting in %s\n", safe_fname(fbuf));
77
78 delete_in_dir(flist, fbuf, file);
79 }
80}
81
82#define SLOT_SIZE (16*1024) /* Desired size in bytes */
83#define PER_SLOT_BITS (SLOT_SIZE * 8) /* Number of bits per slot */
84#define PER_SLOT_INTS (SLOT_SIZE / 4) /* Number of int32s per slot */
85
86static uint32 **delayed_bits = NULL;
87static int delayed_slot_cnt = 0;
88
89static void init_delayed_bits(int max_ndx)
90{
91 delayed_slot_cnt = (max_ndx + PER_SLOT_BITS - 1) / PER_SLOT_BITS;
92
93 if (!(delayed_bits = (uint32**)calloc(delayed_slot_cnt, sizeof (uint32*))))
94 out_of_memory("set_delayed_bit");
95}
96
97static void set_delayed_bit(int ndx)
98{
99 int slot = ndx / PER_SLOT_BITS;
100 ndx %= PER_SLOT_BITS;
101
102 if (!delayed_bits[slot]) {
103 if (!(delayed_bits[slot] = (uint32*)calloc(PER_SLOT_INTS, 4)))
104 out_of_memory("set_delayed_bit");
105 }
106
107 delayed_bits[slot][ndx/32] |= 1u << (ndx % 32);
108}
109
110/* Call this with -1 to start checking from 0. Returns -1 at the end. */
111static int next_delayed_bit(int after)
112{
113 uint32 bits, mask;
114 int i, ndx = after + 1;
115 int slot = ndx / PER_SLOT_BITS;
116 ndx %= PER_SLOT_BITS;
117
118 mask = (1u << (ndx % 32)) - 1;
119 for (i = ndx / 32; slot < delayed_slot_cnt; slot++, i = mask = 0) {
120 if (!delayed_bits[slot])
121 continue;
122 for ( ; i < PER_SLOT_INTS; i++, mask = 0) {
123 if (!(bits = delayed_bits[slot][i] & ~mask))
124 continue;
125 /* The xor magic figures out the lowest enabled bit in
126 * bits, and the switch quickly computes log2(bit). */
127 switch (bits ^ (bits & (bits-1))) {
128#define LOG2(n) case 1u << n: return slot*PER_SLOT_BITS + i*32 + n
129 LOG2(0); LOG2(1); LOG2(2); LOG2(3);
130 LOG2(4); LOG2(5); LOG2(6); LOG2(7);
131 LOG2(8); LOG2(9); LOG2(10); LOG2(11);
132 LOG2(12); LOG2(13); LOG2(14); LOG2(15);
133 LOG2(16); LOG2(17); LOG2(18); LOG2(19);
134 LOG2(20); LOG2(21); LOG2(22); LOG2(23);
135 LOG2(24); LOG2(25); LOG2(26); LOG2(27);
136 LOG2(28); LOG2(29); LOG2(30); LOG2(31);
137 }
138 return -1; /* impossible... */
139 }
140 }
141
142 return -1;
143}
144
145
146/*
147 * get_tmpname() - create a tmp filename for a given filename
148 *
149 * If a tmpdir is defined, use that as the directory to
150 * put it in. Otherwise, the tmp filename is in the same
151 * directory as the given name. Note that there may be no
152 * directory at all in the given name!
153 *
154 * The tmp filename is basically the given filename with a
155 * dot prepended, and .XXXXXX appended (for mkstemp() to
156 * put its unique gunk in). Take care to not exceed
157 * either the MAXPATHLEN or NAME_MAX, esp. the last, as
158 * the basename basically becomes 8 chars longer. In that
159 * case, the original name is shortened sufficiently to
160 * make it all fit.
161 *
162 * Of course, there's no real reason for the tmp name to
163 * look like the original, except to satisfy us humans.
164 * As long as it's unique, rsync will work.
165 */
166
167static int get_tmpname(char *fnametmp, char *fname)
168{
169 char *f;
170 int length = 0;
171 int maxname;
172
173 if (tmpdir) {
174 /* Note: this can't overflow, so the return value is safe */
175 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
176 fnametmp[length++] = '/';
177 fnametmp[length] = '\0'; /* always NULL terminated */
178 }
179
180 if ((f = strrchr(fname, '/')) != NULL) {
181 ++f;
182 if (!tmpdir) {
183 length = f - fname;
184 /* copy up to and including the slash */
185 strlcpy(fnametmp, fname, length + 1);
186 }
187 } else
188 f = fname;
189 fnametmp[length++] = '.';
190 fnametmp[length] = '\0'; /* always NULL terminated */
191
192 maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
193
194 if (maxname < 1) {
195 rprintf(FERROR, "temporary filename too long: %s\n",
196 safe_fname(fname));
197 fnametmp[0] = '\0';
198 return 0;
199 }
200
201 strlcpy(fnametmp + length, f, maxname);
202 strcat(fnametmp + length, ".XXXXXX");
203
204 return 1;
205}
206
207
208static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
209 char *fname, int fd, OFF_T total_size)
210{
211 static char file_sum1[MD4_SUM_LENGTH];
212 static char file_sum2[MD4_SUM_LENGTH];
213 struct map_struct *mapbuf;
214 struct sum_struct sum;
215 int32 len;
216 OFF_T offset = 0;
217 OFF_T offset2;
218 char *data;
219 int32 i;
220 char *map = NULL;
221
222 read_sum_head(f_in, &sum);
223
224 if (fd_r >= 0 && size_r > 0) {
225 int32 read_size = MAX(sum.blength * 2, 16*1024);
226 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
227 if (verbose > 2) {
228 rprintf(FINFO, "recv mapped %s of size %.0f\n",
229 safe_fname(fname_r), (double)size_r);
230 }
231 } else
232 mapbuf = NULL;
233
234 sum_init(checksum_seed);
235
236 while ((i = recv_token(f_in, &data)) != 0) {
237 if (do_progress)
238 show_progress(offset, total_size);
239
240 if (i > 0) {
241 if (verbose > 3) {
242 rprintf(FINFO,"data recv %d at %.0f\n",
243 i,(double)offset);
244 }
245
246 stats.literal_data += i;
247 cleanup_got_literal = 1;
248
249 sum_update(data, i);
250
251 if (fd != -1 && write_file(fd,data,i) != i)
252 goto report_write_error;
253 offset += i;
254 continue;
255 }
256
257 i = -(i+1);
258 offset2 = i * (OFF_T)sum.blength;
259 len = sum.blength;
260 if (i == (int)sum.count-1 && sum.remainder != 0)
261 len = sum.remainder;
262
263 stats.matched_data += len;
264
265 if (verbose > 3) {
266 rprintf(FINFO,
267 "chunk[%d] of size %ld at %.0f offset=%.0f\n",
268 i, (long)len, (double)offset2, (double)offset);
269 }
270
271 if (mapbuf) {
272 map = map_ptr(mapbuf,offset2,len);
273
274 see_token(map, len);
275 sum_update(map, len);
276 }
277
278 if (inplace) {
279 if (offset == offset2 && fd != -1) {
280 if (flush_write_file(fd) < 0)
281 goto report_write_error;
282 offset += len;
283 if (do_lseek(fd, len, SEEK_CUR) != offset) {
284 rsyserr(FERROR, errno,
285 "lseek failed on %s",
286 full_fname(fname));
287 exit_cleanup(RERR_FILEIO);
288 }
289 continue;
290 }
291 }
292 if (fd != -1 && write_file(fd, map, len) != (int)len)
293 goto report_write_error;
294 offset += len;
295 }
296
297 if (flush_write_file(fd) < 0)
298 goto report_write_error;
299
300#ifdef HAVE_FTRUNCATE
301 if (inplace && fd != -1)
302 ftruncate(fd, offset);
303#endif
304
305 if (do_progress)
306 end_progress(total_size);
307
308 if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
309 report_write_error:
310 rsyserr(FERROR, errno, "write failed on %s",
311 full_fname(fname));
312 exit_cleanup(RERR_FILEIO);
313 }
314
315 sum_end(file_sum1);
316
317 if (mapbuf)
318 unmap_file(mapbuf);
319
320 read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
321 if (verbose > 2)
322 rprintf(FINFO,"got file_sum\n");
323 if (fd != -1 && memcmp(file_sum1, file_sum2, MD4_SUM_LENGTH) != 0)
324 return 0;
325 return 1;
326}
327
328
329static void read_gen_name(int fd, char *dirname, char *buf)
330{
331 int dlen;
332 int len = read_byte(fd);
333
334 if (len & 0x80) {
335#if MAXPATHLEN > 32767
336 uchar lenbuf[2];
337 read_buf(fd, (char *)lenbuf, 2);
338 len = (len & ~0x80) * 0x10000 + lenbuf[0] * 0x100 + lenbuf[1];
339#else
340 len = (len & ~0x80) * 0x100 + read_byte(fd);
341#endif
342 }
343
344 if (dirname) {
345 dlen = strlcpy(buf, dirname, MAXPATHLEN);
346 buf[dlen++] = '/';
347 } else
348 dlen = 0;
349
350 if (dlen + len >= MAXPATHLEN) {
351 rprintf(FERROR, "bogus data on generator name pipe\n");
352 exit_cleanup(RERR_PROTOCOL);
353 }
354
355 read_sbuf(fd, buf + dlen, len);
356}
357
358
359static void discard_receive_data(int f_in, OFF_T length)
360{
361 receive_data(f_in, NULL, -1, 0, NULL, -1, length);
362}
363
364
365/**
366 * main routine for receiver process.
367 *
368 * Receiver process runs on the same host as the generator process. */
369int recv_files(int f_in, struct file_list *flist, char *local_name,
370 int f_in_name)
371{
372 int next_gen_i = -1;
373 int fd1,fd2;
374 STRUCT_STAT st;
375 int iflags;
376 char *fname, fbuf[MAXPATHLEN];
377 char template[MAXPATHLEN];
378 char fnametmp[MAXPATHLEN];
379 char *fnamecmp, *partialptr, numbuf[4];
380 char fnamecmpbuf[MAXPATHLEN];
381 struct file_struct *file;
382 struct stats initial_stats;
383 int save_make_backups = make_backups;
384 int itemizing = am_daemon ? daemon_log_format_has_i
385 : !am_server && log_format_has_i;
386 int i, recv_ok, phase = 0;
387
388 if (verbose > 2)
389 rprintf(FINFO,"recv_files(%d) starting\n",flist->count);
390
391 if (flist->hlink_pool) {
392 pool_destroy(flist->hlink_pool);
393 flist->hlink_pool = NULL;
394 }
395
396 if (delay_updates)
397 init_delayed_bits(flist->count);
398
399 while (1) {
400 cleanup_disable();
401
402 i = read_int(f_in);
403 if (i == -1) {
404 if (read_batch) {
405 if (next_gen_i != flist->count) {
406 do {
407 if (f_in_name >= 0
408 && next_gen_i >= 0)
409 read_byte(f_in_name);
410 } while (read_int(batch_gen_fd) != -1);
411 }
412 next_gen_i = -1;
413 }
414
415 if (phase)
416 break;
417
418 phase = 1;
419 csum_length = SUM_LENGTH;
420 if (verbose > 2)
421 rprintf(FINFO, "recv_files phase=%d\n", phase);
422 send_msg(MSG_DONE, "", 0);
423 if (keep_partial && !partial_dir)
424 make_backups = 0; /* prevents double backup */
425 continue;
426 }
427
428 if (i < 0 || i >= flist->count) {
429 rprintf(FERROR,"Invalid file index %d in recv_files (count=%d)\n",
430 i, flist->count);
431 exit_cleanup(RERR_PROTOCOL);
432 }
433
434 file = flist->files[i];
435 fname = local_name ? local_name : f_name_to(file, fbuf);
436
437 if (verbose > 2)
438 rprintf(FINFO, "recv_files(%s)\n", safe_fname(fname));
439
440 if (protocol_version >= 29) {
441 iflags = read_shortint(f_in);
442 if (!(iflags & ITEM_UPDATING) || !S_ISREG(file->mode)) {
443 int see_item = itemizing && (iflags || verbose > 1);
444 if (am_server) {
445 if (am_daemon && !dry_run && see_item)
446 log_recv(file, &stats, iflags);
447 } else if (see_item || iflags & ITEM_UPDATING
448 || (S_ISDIR(file->mode)
449 && iflags & ITEM_REPORT_TIME))
450 log_recv(file, &stats, iflags);
451 continue;
452 }
453 } else
454 iflags = ITEM_UPDATING | ITEM_MISSING_DATA;
455
456 if (!S_ISREG(file->mode)) {
457 rprintf(FERROR, "[%s] got index of non-regular file: %d\n",
458 who_am_i(), i);
459 exit_cleanup(RERR_PROTOCOL);
460 }
461
462 stats.current_file_index = i;
463 stats.num_transferred_files++;
464 stats.total_transferred_size += file->length;
465 cleanup_got_literal = 0;
466
467 if (server_filter_list.head
468 && check_filter(&server_filter_list, fname, 0) < 0) {
469 rprintf(FERROR, "attempt to hack rsync failed.\n");
470 exit_cleanup(RERR_PROTOCOL);
471 }
472
473 if (dry_run) { /* log the transfer */
474 if (!am_server && log_format)
475 log_recv(file, &stats, iflags);
476 continue;
477 }
478
479 if (read_batch) {
480 while (i > next_gen_i) {
481 if (f_in_name >= 0 && next_gen_i >= 0)
482 read_byte(f_in_name);
483 next_gen_i = read_int(batch_gen_fd);
484 if (next_gen_i == -1)
485 next_gen_i = flist->count;
486 }
487 if (i < next_gen_i) {
488 rprintf(FINFO, "skipping update for \"%s\"\n",
489 safe_fname(fname));
490 discard_receive_data(f_in, file->length);
491 continue;
492 }
493 next_gen_i = -1;
494 }
495
496 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
497
498 if (f_in_name >= 0) {
499 uchar j;
500 switch (j = read_byte(f_in_name)) {
501 case FNAMECMP_FNAME:
502 fnamecmp = fname;
503 break;
504 case FNAMECMP_PARTIAL_DIR:
505 fnamecmp = partialptr ? partialptr : fname;
506 break;
507 case FNAMECMP_BACKUP:
508 fnamecmp = get_backup_name(fname);
509 break;
510 case FNAMECMP_FUZZY:
511 read_gen_name(f_in_name, file->dirname, fnamecmpbuf);
512 fnamecmp = fnamecmpbuf;
513 break;
514 default:
515 if (j >= basis_dir_cnt) {
516 rprintf(FERROR,
517 "invalid basis_dir index: %d.\n",
518 j);
519 exit_cleanup(RERR_PROTOCOL);
520 }
521 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
522 basis_dir[j], fname);
523 fnamecmp = fnamecmpbuf;
524 break;
525 }
526 } else
527 fnamecmp = fname;
528
529 initial_stats = stats;
530
531 /* open the file */
532 fd1 = do_open(fnamecmp, O_RDONLY, 0);
533
534 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
535 rsyserr(FERROR, errno, "fstat %s failed",
536 full_fname(fnamecmp));
537 discard_receive_data(f_in, file->length);
538 close(fd1);
539 continue;
540 }
541
542 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
543 /* this special handling for directories
544 * wouldn't be necessary if robust_rename()
545 * and the underlying robust_unlink could cope
546 * with directories
547 */
548 rprintf(FERROR,"recv_files: %s is a directory\n",
549 full_fname(fnamecmp));
550 discard_receive_data(f_in, file->length);
551 close(fd1);
552 continue;
553 }
554
555 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
556 close(fd1);
557 fd1 = -1;
558 }
559
560 if (fd1 != -1 && !preserve_perms) {
561 /* if the file exists already and we aren't preserving
562 * permissions then act as though the remote end sent
563 * us the file permissions we already have */
564 file->mode = st.st_mode;
565 }
566
567 /* We now check to see if we are writing file "inplace" */
568 if (inplace) {
569 fd2 = do_open(fname, O_WRONLY|O_CREAT, 0);
570 if (fd2 == -1) {
571 rsyserr(FERROR, errno, "open %s failed",
572 full_fname(fname));
573 discard_receive_data(f_in, file->length);
574 if (fd1 != -1)
575 close(fd1);
576 continue;
577 }
578 } else {
579 if (!get_tmpname(fnametmp,fname)) {
580 discard_receive_data(f_in, file->length);
581 if (fd1 != -1)
582 close(fd1);
583 continue;
584 }
585
586 strlcpy(template, fnametmp, sizeof template);
587
588 /* we initially set the perms without the
589 * setuid/setgid bits to ensure that there is no race
590 * condition. They are then correctly updated after
591 * the lchown. Thanks to snabb@epipe.fi for pointing
592 * this out. We also set it initially without group
593 * access because of a similar race condition. */
594 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
595
596 /* in most cases parent directories will already exist
597 * because their information should have been previously
598 * transferred, but that may not be the case with -R */
599 if (fd2 == -1 && relative_paths && errno == ENOENT
600 && create_directory_path(fnametmp, orig_umask) == 0) {
601 strlcpy(fnametmp, template, sizeof fnametmp);
602 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
603 }
604 if (fd2 == -1) {
605 rsyserr(FERROR, errno, "mkstemp %s failed",
606 full_fname(fnametmp));
607 discard_receive_data(f_in, file->length);
608 if (fd1 != -1)
609 close(fd1);
610 continue;
611 }
612
613 if (partialptr)
614 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
615 }
616
617 /* log the transfer */
618 if (log_before_transfer)
619 log_recv(file, &initial_stats, iflags);
620 else if (!am_server && verbose && do_progress)
621 rprintf(FINFO, "%s\n", safe_fname(fname));
622
623 /* recv file data */
624 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
625 fname, fd2, file->length);
626
627 if (!log_before_transfer)
628 log_recv(file, &initial_stats, iflags);
629
630 if (fd1 != -1)
631 close(fd1);
632 if (close(fd2) < 0) {
633 rsyserr(FERROR, errno, "close failed on %s",
634 full_fname(fnametmp));
635 exit_cleanup(RERR_FILEIO);
636 }
637
638 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
639 finish_transfer(fname, fnametmp, file, recv_ok, 1);
640 if (partialptr != fname && fnamecmp == partialptr) {
641 do_unlink(partialptr);
642 handle_partial_dir(partialptr, PDIR_DELETE);
643 }
644 } else if (keep_partial && partialptr
645 && handle_partial_dir(partialptr, PDIR_CREATE)) {
646 finish_transfer(partialptr, fnametmp, file, recv_ok,
647 !partial_dir);
648 if (delay_updates && recv_ok) {
649 set_delayed_bit(i);
650 recv_ok = -1;
651 }
652 } else {
653 partialptr = NULL;
654 do_unlink(fnametmp);
655 }
656
657 cleanup_disable();
658
659 if (recv_ok) {
660 if (remove_sent_files && recv_ok > 0) {
661 SIVAL(numbuf, 0, i);
662 send_msg(MSG_SUCCESS, numbuf, 4);
663 }
664 } else {
665 int msgtype = csum_length == SUM_LENGTH || read_batch ?
666 FERROR : FINFO;
667 if (msgtype == FERROR || verbose) {
668 char *errstr, *redostr, *keptstr;
669 if (!(keep_partial && partialptr) && !inplace)
670 keptstr = "discarded";
671 else if (partial_dir)
672 keptstr = "put into partial-dir";
673 else
674 keptstr = "retained";
675 if (msgtype == FERROR) {
676 errstr = "ERROR";
677 redostr = "";
678 } else {
679 errstr = "WARNING";
680 redostr = " (will try again)";
681 }
682 rprintf(msgtype,
683 "%s: %s failed verification -- update %s%s.\n",
684 errstr, safe_fname(fname),
685 keptstr, redostr);
686 }
687 if (csum_length != SUM_LENGTH) {
688 SIVAL(numbuf, 0, i);
689 send_msg(MSG_REDO, numbuf, 4);
690 }
691 }
692 }
693 make_backups = save_make_backups;
694
695 if (delay_updates) {
696 for (i = -1; (i = next_delayed_bit(i)) >= 0; ) {
697 struct file_struct *file = flist->files[i];
698 fname = local_name ? local_name : f_name(file);
699 partialptr = partial_dir_fname(fname);
700 if (partialptr) {
701 if (make_backups && !make_backup(fname))
702 continue;
703 if (verbose > 2) {
704 rprintf(FINFO, "renaming %s to %s\n",
705 safe_fname(partialptr),
706 safe_fname(fname));
707 }
708 if (do_rename(partialptr, fname) < 0) {
709 rsyserr(FERROR, errno,
710 "rename failed for %s (from %s)",
711 full_fname(fname),
712 safe_fname(partialptr));
713 } else {
714 if (remove_sent_files) {
715 SIVAL(numbuf, 0, i);
716 send_msg(MSG_SUCCESS,numbuf,4);
717 }
718 handle_partial_dir(partialptr,
719 PDIR_DELETE);
720 }
721 }
722 }
723 }
724
725 if (delete_after && !local_name && flist->count > 0)
726 delete_files(flist);
727
728 if (verbose > 2)
729 rprintf(FINFO,"recv_files finished\n");
730
731 return 0;
732}