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