8518fbfdab55416ae4f872f27787a0c83ed13acb
[rsync/rsync.git] / receiver.c
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
23 extern int verbose;
24 extern int do_xfers;
25 extern int am_daemon;
26 extern int am_server;
27 extern int do_progress;
28 extern int log_before_transfer;
29 extern int log_format_has_i;
30 extern int daemon_log_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 keep_dirlinks;
38 extern int preserve_hard_links;
39 extern int preserve_perms;
40 extern int io_error;
41 extern int basis_dir_cnt;
42 extern int make_backups;
43 extern int cleanup_got_literal;
44 extern int remove_sent_files;
45 extern int module_id;
46 extern int ignore_errors;
47 extern int append_mode;
48 extern int sparse_files;
49 extern int keep_partial;
50 extern int checksum_seed;
51 extern int inplace;
52 extern int delay_updates;
53 extern struct stats stats;
54 extern char *log_format;
55 extern char *tmpdir;
56 extern char *partial_dir;
57 extern char *basis_dir[];
58 extern struct file_list *the_file_list;
59 extern struct filter_list_struct server_filter_list;
60
61 static struct bitbag *delayed_bits = NULL;
62 static int phase = 0;
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
86 static int get_tmpname(char *fnametmp, char *fname)
87 {
88         char *f;
89         int     length = 0;
90         int     maxname;
91
92         if (tmpdir) {
93                 /* Note: this can't overflow, so the return value is safe */
94                 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
95                 fnametmp[length++] = '/';
96                 fnametmp[length] = '\0';        /* always NULL terminated */
97         }
98
99         if ((f = strrchr(fname, '/')) != NULL) {
100                 ++f;
101                 if (!tmpdir) {
102                         length = f - fname;
103                         /* copy up to and including the slash */
104                         strlcpy(fnametmp, fname, length + 1);
105                 }
106         } else
107                 f = fname;
108         fnametmp[length++] = '.';
109         fnametmp[length] = '\0';                /* always NULL terminated */
110
111         maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
112
113         if (maxname < 1) {
114                 rprintf(FERROR, "temporary filename too long: %s\n", fname);
115                 fnametmp[0] = '\0';
116                 return 0;
117         }
118
119         strlcpy(fnametmp + length, f, maxname);
120         strcat(fnametmp + length, ".XXXXXX");
121
122         return 1;
123 }
124
125
126 static int receive_data(int f_in, char *fname_r, int fd_r, OFF_T size_r,
127                         char *fname, int fd, OFF_T total_size)
128 {
129         static char file_sum1[MD4_SUM_LENGTH];
130         static char file_sum2[MD4_SUM_LENGTH];
131         struct map_struct *mapbuf;
132         struct sum_struct sum;
133         int32 len;
134         OFF_T offset = 0;
135         OFF_T offset2;
136         char *data;
137         int32 i;
138         char *map = NULL;
139
140         read_sum_head(f_in, &sum);
141
142         if (fd_r >= 0 && size_r > 0) {
143                 int32 read_size = MAX(sum.blength * 2, 16*1024);
144                 mapbuf = map_file(fd_r, size_r, read_size, sum.blength);
145                 if (verbose > 2) {
146                         rprintf(FINFO, "recv mapped %s of size %.0f\n",
147                                 fname_r, (double)size_r);
148                 }
149         } else
150                 mapbuf = NULL;
151
152         sum_init(checksum_seed);
153
154         if (append_mode) {
155                 OFF_T j;
156                 sum.flength = (OFF_T)sum.count * sum.blength;
157                 if (sum.remainder)
158                         sum.flength -= sum.blength - sum.remainder;
159                 for (j = CHUNK_SIZE; j < sum.flength; j += CHUNK_SIZE) {
160                         if (do_progress)
161                                 show_progress(offset, total_size);
162                         sum_update(map_ptr(mapbuf, offset, CHUNK_SIZE),
163                                    CHUNK_SIZE);
164                         offset = j;
165                 }
166                 if (offset < sum.flength) {
167                         int32 len = sum.flength - offset;
168                         if (do_progress)
169                                 show_progress(offset, total_size);
170                         sum_update(map_ptr(mapbuf, offset, len), len);
171                         offset = sum.flength;
172                 }
173                 if (fd != -1 && do_lseek(fd, offset, SEEK_SET) != offset) {
174                         rsyserr(FERROR, errno, "lseek failed on %s",
175                                 full_fname(fname));
176                         exit_cleanup(RERR_FILEIO);
177                 }
178         }
179
180         while ((i = recv_token(f_in, &data)) != 0) {
181                 if (do_progress)
182                         show_progress(offset, total_size);
183
184                 if (i > 0) {
185                         if (verbose > 3) {
186                                 rprintf(FINFO,"data recv %d at %.0f\n",
187                                         i,(double)offset);
188                         }
189
190                         stats.literal_data += i;
191                         cleanup_got_literal = 1;
192
193                         sum_update(data, i);
194
195                         if (fd != -1 && write_file(fd,data,i) != i)
196                                 goto report_write_error;
197                         offset += i;
198                         continue;
199                 }
200
201                 i = -(i+1);
202                 offset2 = i * (OFF_T)sum.blength;
203                 len = sum.blength;
204                 if (i == (int)sum.count-1 && sum.remainder != 0)
205                         len = sum.remainder;
206
207                 stats.matched_data += len;
208
209                 if (verbose > 3) {
210                         rprintf(FINFO,
211                                 "chunk[%d] of size %ld at %.0f offset=%.0f\n",
212                                 i, (long)len, (double)offset2, (double)offset);
213                 }
214
215                 if (mapbuf) {
216                         map = map_ptr(mapbuf,offset2,len);
217
218                         see_token(map, len);
219                         sum_update(map, len);
220                 }
221
222                 if (inplace) {
223                         if (offset == offset2 && fd != -1) {
224                                 if (flush_write_file(fd) < 0)
225                                         goto report_write_error;
226                                 offset += len;
227                                 if (do_lseek(fd, len, SEEK_CUR) != offset) {
228                                         rsyserr(FERROR, errno,
229                                                 "lseek failed on %s",
230                                                 full_fname(fname));
231                                         exit_cleanup(RERR_FILEIO);
232                                 }
233                                 continue;
234                         }
235                 }
236                 if (fd != -1 && map && write_file(fd, map, len) != (int)len)
237                         goto report_write_error;
238                 offset += len;
239         }
240
241         if (flush_write_file(fd) < 0)
242                 goto report_write_error;
243
244 #ifdef HAVE_FTRUNCATE
245         if (inplace && fd != -1)
246                 ftruncate(fd, offset);
247 #endif
248
249         if (do_progress)
250                 end_progress(total_size);
251
252         if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
253             report_write_error:
254                 rsyserr(FERROR, errno, "write failed on %s",
255                         full_fname(fname));
256                 exit_cleanup(RERR_FILEIO);
257         }
258
259         sum_end(file_sum1);
260
261         if (mapbuf)
262                 unmap_file(mapbuf);
263
264         read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
265         if (verbose > 2)
266                 rprintf(FINFO,"got file_sum\n");
267         if (fd != -1 && memcmp(file_sum1, file_sum2, MD4_SUM_LENGTH) != 0)
268                 return 0;
269         return 1;
270 }
271
272
273 static void discard_receive_data(int f_in, OFF_T length)
274 {
275         receive_data(f_in, NULL, -1, 0, NULL, -1, length);
276 }
277
278 static void handle_delayed_updates(struct file_list *flist, char *local_name)
279 {
280         char *fname, *partialptr, numbuf[4];
281         int i;
282
283         for (i = -1; (i = bitbag_next_bit(delayed_bits, i)) >= 0; ) {
284                 struct file_struct *file = flist->files[i];
285                 fname = local_name ? local_name : f_name(file, NULL);
286                 if ((partialptr = partial_dir_fname(fname)) != NULL) {
287                         if (make_backups && !make_backup(fname))
288                                 continue;
289                         if (verbose > 2) {
290                                 rprintf(FINFO, "renaming %s to %s\n",
291                                         partialptr, fname);
292                         }
293                         /* We don't use robust_rename() here because the
294                          * partial-dir must be on the same drive. */
295                         if (do_rename(partialptr, fname) < 0) {
296                                 rsyserr(FERROR, errno,
297                                         "rename failed for %s (from %s)",
298                                         full_fname(fname), partialptr);
299                         } else {
300                                 if (remove_sent_files
301                                     || (preserve_hard_links
302                                      && file->link_u.links)) {
303                                         SIVAL(numbuf, 0, i);
304                                         send_msg(MSG_SUCCESS,numbuf,4);
305                                 }
306                                 handle_partial_dir(partialptr, PDIR_DELETE);
307                         }
308                 }
309         }
310 }
311
312 static 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. */
333 int 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, numbuf[4];
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_daemon ? daemon_log_format_has_i
349                       : !am_server && log_format_has_i;
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         while (1) {
365                 cleanup_disable();
366
367                 i = read_int(f_in);
368                 if (i == -1) {
369                         if (read_batch) {
370                                 get_next_gen_i(batch_gen_fd, next_gen_i,
371                                                flist->count);
372                                 next_gen_i = -1;
373                         }
374                         if (++phase > max_phase)
375                                 break;
376                         csum_length = SUM_LENGTH;
377                         if (verbose > 2)
378                                 rprintf(FINFO, "recv_files phase=%d\n", phase);
379                         if (phase == 2 && delay_updates)
380                                 handle_delayed_updates(flist, local_name);
381                         send_msg(MSG_DONE, "", 0);
382                         if (keep_partial && !partial_dir)
383                                 make_backups = 0; /* prevents double backup */
384                         if (append_mode) {
385                                 append_mode = 0;
386                                 sparse_files = 0;
387                         }
388                         continue;
389                 }
390
391                 iflags = read_item_attrs(f_in, -1, i, &fnamecmp_type,
392                                          xname, &xlen);
393                 if (iflags == ITEM_IS_NEW) /* no-op packet */
394                         continue;
395
396                 file = flist->files[i];
397                 fname = local_name ? local_name : f_name(file, fbuf);
398
399                 if (verbose > 2)
400                         rprintf(FINFO, "recv_files(%s)\n", fname);
401
402                 if (!(iflags & ITEM_TRANSFER)) {
403                         maybe_log_item(file, iflags, itemizing, xname);
404                         continue;
405                 }
406                 if (phase == 2) {
407                         rprintf(FERROR,
408                                 "got transfer request in phase 2 [%s]\n",
409                                 who_am_i());
410                         exit_cleanup(RERR_PROTOCOL);
411                 }
412
413                 stats.current_file_index = i;
414                 stats.num_transferred_files++;
415                 stats.total_transferred_size += file->length;
416                 cleanup_got_literal = 0;
417
418                 if (server_filter_list.head
419                     && check_filter(&server_filter_list, fname, 0) < 0) {
420                         rprintf(FERROR, "attempt to hack rsync failed.\n");
421                         exit_cleanup(RERR_PROTOCOL);
422                 }
423
424                 if (!do_xfers) { /* log the transfer */
425                         if (!am_server && log_format)
426                                 log_item(file, &stats, iflags, NULL);
427                         if (read_batch)
428                                 discard_receive_data(f_in, file->length);
429                         continue;
430                 }
431                 if (write_batch < 0) {
432                         log_item(file, &stats, iflags, NULL);
433                         if (!am_server)
434                                 discard_receive_data(f_in, file->length);
435                         continue;
436                 }
437
438                 if (read_batch) {
439                         next_gen_i = get_next_gen_i(batch_gen_fd, next_gen_i, i);
440                         if (i < next_gen_i) {
441                                 rprintf(FINFO,
442                                         "(Skipping batched update for \"%s\")\n",
443                                         fname);
444                                 discard_receive_data(f_in, file->length);
445                                 continue;
446                         }
447                         next_gen_i = -1;
448                 }
449
450                 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
451
452                 if (protocol_version >= 29) {
453                         switch (fnamecmp_type) {
454                         case FNAMECMP_FNAME:
455                                 fnamecmp = fname;
456                                 break;
457                         case FNAMECMP_PARTIAL_DIR:
458                                 fnamecmp = partialptr;
459                                 break;
460                         case FNAMECMP_BACKUP:
461                                 fnamecmp = get_backup_name(fname);
462                                 break;
463                         case FNAMECMP_FUZZY:
464                                 if (file->dirname) {
465                                         pathjoin(fnamecmpbuf, MAXPATHLEN,
466                                                  file->dirname, xname);
467                                         fnamecmp = fnamecmpbuf;
468                                 } else
469                                         fnamecmp = xname;
470                                 break;
471                         default:
472                                 if (fnamecmp_type >= basis_dir_cnt) {
473                                         rprintf(FERROR,
474                                                 "invalid basis_dir index: %d.\n",
475                                                 fnamecmp_type);
476                                         exit_cleanup(RERR_PROTOCOL);
477                                 }
478                                 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
479                                          basis_dir[fnamecmp_type], fname);
480                                 fnamecmp = fnamecmpbuf;
481                                 break;
482                         }
483                         if (!fnamecmp || (server_filter_list.head
484                           && check_filter(&server_filter_list, fname, 0) < 0))
485                                 fnamecmp = fname;
486                 } else {
487                         /* Reminder: --inplace && --partial-dir are never
488                          * enabled at the same time. */
489                         if (inplace && make_backups) {
490                                 if (!(fnamecmp = get_backup_name(fname)))
491                                         fnamecmp = fname;
492                         } else if (partial_dir && partialptr)
493                                 fnamecmp = partialptr;
494                         else
495                                 fnamecmp = fname;
496                 }
497
498                 initial_stats = stats;
499
500                 /* open the file */
501                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
502
503                 if (fd1 == -1 && protocol_version < 29) {
504                         if (fnamecmp != fname) {
505                                 fnamecmp = fname;
506                                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
507                         }
508
509                         if (fd1 == -1 && basis_dir[0]) {
510                                 /* pre-29 allowed only one alternate basis */
511                                 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
512                                          basis_dir[0], fname);
513                                 fnamecmp = fnamecmpbuf;
514                                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
515                         }
516                 }
517
518                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
519                         rsyserr(FERROR, errno, "fstat %s failed",
520                                 full_fname(fnamecmp));
521                         discard_receive_data(f_in, file->length);
522                         close(fd1);
523                         continue;
524                 }
525
526                 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
527                         /* this special handling for directories
528                          * wouldn't be necessary if robust_rename()
529                          * and the underlying robust_unlink could cope
530                          * with directories
531                          */
532                         rprintf(FERROR,"recv_files: %s is a directory\n",
533                                 full_fname(fnamecmp));
534                         discard_receive_data(f_in, file->length);
535                         close(fd1);
536                         continue;
537                 }
538
539                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
540                         close(fd1);
541                         fd1 = -1;
542                 }
543
544                 /* If we're not preserving permissions, change the file-list's
545                  * mode based on the local permissions and some heuristics. */
546                 if (!preserve_perms) {
547                         int exists = fd1 != -1;
548                         file->mode = dest_mode(file->mode, st.st_mode, exists);
549                 }
550
551                 /* We now check to see if we are writing file "inplace" */
552                 if (inplace)  {
553                         fd2 = do_open(fname, O_WRONLY|O_CREAT, 0600);
554                         if (fd2 == -1) {
555                                 rsyserr(FERROR, errno, "open %s failed",
556                                         full_fname(fname));
557                                 discard_receive_data(f_in, file->length);
558                                 if (fd1 != -1)
559                                         close(fd1);
560                                 continue;
561                         }
562                 } else {
563                         if (!get_tmpname(fnametmp,fname)) {
564                                 discard_receive_data(f_in, file->length);
565                                 if (fd1 != -1)
566                                         close(fd1);
567                                 continue;
568                         }
569
570                         /* we initially set the perms without the
571                          * setuid/setgid bits to ensure that there is no race
572                          * condition. They are then correctly updated after
573                          * the lchown. Thanks to snabb@epipe.fi for pointing
574                          * this out.  We also set it initially without group
575                          * access because of a similar race condition. */
576                         fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
577
578                         /* in most cases parent directories will already exist
579                          * because their information should have been previously
580                          * transferred, but that may not be the case with -R */
581                         if (fd2 == -1 && relative_paths && errno == ENOENT
582                             && create_directory_path(fnametmp) == 0) {
583                                 /* Get back to name with XXXXXX in it. */
584                                 get_tmpname(fnametmp, fname);
585                                 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
586                         }
587                         if (fd2 == -1) {
588                                 rsyserr(FERROR, errno, "mkstemp %s failed",
589                                         full_fname(fnametmp));
590                                 discard_receive_data(f_in, file->length);
591                                 if (fd1 != -1)
592                                         close(fd1);
593                                 continue;
594                         }
595
596                         if (keep_partial)
597                                 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
598                 }
599
600                 /* log the transfer */
601                 if (log_before_transfer)
602                         log_item(file, &initial_stats, iflags, NULL);
603                 else if (!am_server && verbose && do_progress)
604                         rprintf(FINFO, "%s\n", fname);
605
606                 /* recv file data */
607                 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
608                                        fname, fd2, file->length);
609
610                 if (!log_before_transfer)
611                         log_item(file, &initial_stats, iflags, NULL);
612
613                 if (fd1 != -1)
614                         close(fd1);
615                 if (close(fd2) < 0) {
616                         rsyserr(FERROR, errno, "close failed on %s",
617                                 full_fname(fnametmp));
618                         exit_cleanup(RERR_FILEIO);
619                 }
620
621                 if ((recv_ok && (!delay_updates || !partialptr)) || inplace) {
622                         if (partialptr == fname || *partial_dir == '/')
623                                 partialptr = NULL;
624                         finish_transfer(fname, fnametmp, partialptr,
625                                         file, recv_ok, 1);
626                         if (fnamecmp == partialptr) {
627                                 do_unlink(partialptr);
628                                 handle_partial_dir(partialptr, PDIR_DELETE);
629                         }
630                 } else if (keep_partial && partialptr
631                     && handle_partial_dir(partialptr, PDIR_CREATE)) {
632                         finish_transfer(partialptr, fnametmp, NULL,
633                                         file, recv_ok, !partial_dir);
634                         if (delay_updates && recv_ok) {
635                                 bitbag_set_bit(delayed_bits, i);
636                                 recv_ok = -1;
637                         }
638                 } else {
639                         partialptr = NULL;
640                         do_unlink(fnametmp);
641                 }
642
643                 cleanup_disable();
644
645                 if (recv_ok > 0) {
646                         if (remove_sent_files
647                             || (preserve_hard_links && file->link_u.links)) {
648                                 SIVAL(numbuf, 0, i);
649                                 send_msg(MSG_SUCCESS, numbuf, 4);
650                         }
651                 } else if (!recv_ok) {
652                         int msgtype = phase || read_batch ? FERROR : FINFO;
653                         if (msgtype == FERROR || verbose) {
654                                 char *errstr, *redostr, *keptstr;
655                                 if (!(keep_partial && partialptr) && !inplace)
656                                         keptstr = "discarded";
657                                 else if (partial_dir)
658                                         keptstr = "put into partial-dir";
659                                 else
660                                         keptstr = "retained";
661                                 if (msgtype == FERROR) {
662                                         errstr = "ERROR";
663                                         redostr = "";
664                                 } else {
665                                         errstr = "WARNING";
666                                         redostr = " (will try again)";
667                                 }
668                                 rprintf(msgtype,
669                                         "%s: %s failed verification -- update %s%s.\n",
670                                         errstr, fname, keptstr, redostr);
671                         }
672                         if (!phase) {
673                                 SIVAL(numbuf, 0, i);
674                                 send_msg(MSG_REDO, numbuf, 4);
675                         }
676                 }
677         }
678         make_backups = save_make_backups;
679
680         if (phase == 2 && delay_updates) /* for protocol_version < 29 */
681                 handle_delayed_updates(flist, local_name);
682
683         if (verbose > 2)
684                 rprintf(FINFO,"recv_files finished\n");
685
686         return 0;
687 }