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