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