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