- If recv_files() is sent the index of a directory, complain about it
[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 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                 if (S_ISDIR(file->mode)) {
347                         rprintf(FERROR, "[%s] got index of directory: %d\n",
348                                 who_am_i(), i);
349                         exit_cleanup(RERR_PROTOCOL);
350                 }
351
352                 stats.current_file_index = i;
353                 stats.num_transferred_files++;
354                 stats.total_transferred_size += file->length;
355                 cleanup_got_literal = 0;
356
357                 fname = local_name ? local_name : f_name_to(file, fbuf);
358
359                 if (server_filter_list.head
360                     && check_filter(&server_filter_list, fname, 0) < 0) {
361                         rprintf(FERROR, "attempt to hack rsync failed.\n");
362                         exit_cleanup(RERR_PROTOCOL);
363                 }
364
365                 if (verbose > 2)
366                         rprintf(FINFO, "recv_files(%s)\n", safe_fname(fname));
367
368                 if (dry_run) {
369                         if (!am_server && verbose) /* log the transfer */
370                                 rprintf(FINFO, "%s\n", safe_fname(fname));
371                         continue;
372                 }
373
374                 initial_stats = stats;
375
376                 if (read_batch) {
377                         while (i > next_gen_i) {
378                                 if (f_in_name >= 0 && next_gen_i >= 0)
379                                         read_byte(f_in_name);
380                                 next_gen_i = read_int(batch_gen_fd);
381                                 if (next_gen_i == -1)
382                                         next_gen_i = flist->count;
383                         }
384                         if (i < next_gen_i) {
385                                 rprintf(FINFO, "skipping update for \"%s\"\n",
386                                         safe_fname(fname));
387                                 discard_receive_data(f_in, file->length);
388                                 continue;
389                         }
390                         next_gen_i = -1;
391                 }
392
393                 partialptr = partial_dir ? partial_dir_fname(fname) : fname;
394
395                 if (f_in_name >= 0) {
396                         uchar j;
397                         switch (j = read_byte(f_in_name)) {
398                         case FNAMECMP_FNAME:
399                                 fnamecmp = fname;
400                                 break;
401                         case FNAMECMP_PARTIAL_DIR:
402                                 fnamecmp = partialptr ? partialptr : fname;
403                                 break;
404                         case FNAMECMP_BACKUP:
405                                 fnamecmp = get_backup_name(fname);
406                                 break;
407                         default:
408                                 if (j >= basis_dir_cnt) {
409                                         rprintf(FERROR,
410                                                 "invalid basis_dir index: %d.\n",
411                                                 j);
412                                         exit_cleanup(RERR_PROTOCOL);
413                                 }
414                                 pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
415                                          basis_dir[j], fname);
416                                 fnamecmp = fnamecmpbuf;
417                                 break;
418                         }
419                 } else
420                         fnamecmp = fname;
421
422                 /* open the file */
423                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
424
425                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
426                         rsyserr(FERROR, errno, "fstat %s failed",
427                                 full_fname(fnamecmp));
428                         discard_receive_data(f_in, file->length);
429                         close(fd1);
430                         continue;
431                 }
432
433                 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
434                         /* this special handling for directories
435                          * wouldn't be necessary if robust_rename()
436                          * and the underlying robust_unlink could cope
437                          * with directories
438                          */
439                         rprintf(FERROR,"recv_files: %s is a directory\n",
440                                 full_fname(fnamecmp));
441                         discard_receive_data(f_in, file->length);
442                         close(fd1);
443                         continue;
444                 }
445
446                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
447                         close(fd1);
448                         fd1 = -1;
449                 }
450
451                 if (fd1 != -1 && !preserve_perms) {
452                         /* if the file exists already and we aren't preserving
453                          * permissions then act as though the remote end sent
454                          * us the file permissions we already have */
455                         file->mode = st.st_mode;
456                 }
457
458                 /* We now check to see if we are writing file "inplace" */
459                 if (inplace)  {
460                         fd2 = do_open(fname, O_WRONLY|O_CREAT, 0);
461                         if (fd2 == -1) {
462                                 rsyserr(FERROR, errno, "open %s failed",
463                                         full_fname(fname));
464                                 discard_receive_data(f_in, file->length);
465                                 if (fd1 != -1)
466                                         close(fd1);
467                                 continue;
468                         }
469                 } else {
470                         if (!get_tmpname(fnametmp,fname)) {
471                                 discard_receive_data(f_in, file->length);
472                                 if (fd1 != -1)
473                                         close(fd1);
474                                 continue;
475                         }
476
477                         strlcpy(template, fnametmp, sizeof template);
478
479                         /* we initially set the perms without the
480                          * setuid/setgid bits to ensure that there is no race
481                          * condition. They are then correctly updated after
482                          * the lchown. Thanks to snabb@epipe.fi for pointing
483                          * this out.  We also set it initially without group
484                          * access because of a similar race condition. */
485                         fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
486
487                         /* in most cases parent directories will already exist
488                          * because their information should have been previously
489                          * transferred, but that may not be the case with -R */
490                         if (fd2 == -1 && relative_paths && errno == ENOENT
491                             && create_directory_path(fnametmp, orig_umask) == 0) {
492                                 strlcpy(fnametmp, template, sizeof fnametmp);
493                                 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
494                         }
495                         if (fd2 == -1) {
496                                 rsyserr(FERROR, errno, "mkstemp %s failed",
497                                         full_fname(fnametmp));
498                                 discard_receive_data(f_in, file->length);
499                                 if (fd1 != -1)
500                                         close(fd1);
501                                 continue;
502                         }
503
504                         if (partialptr)
505                                 cleanup_set(fnametmp, partialptr, file, fd1, fd2);
506                 }
507
508                 if (!am_server && verbose) /* log the transfer */
509                         rprintf(FINFO, "%s\n", safe_fname(fname));
510
511                 /* recv file data */
512                 recv_ok = receive_data(f_in, fnamecmp, fd1, st.st_size,
513                                        fname, fd2, file->length);
514
515                 log_recv(file, &initial_stats);
516
517                 if (fd1 != -1)
518                         close(fd1);
519                 if (close(fd2) < 0) {
520                         rsyserr(FERROR, errno, "close failed on %s",
521                                 full_fname(fnametmp));
522                         exit_cleanup(RERR_FILEIO);
523                 }
524
525                 if ((recv_ok && !delay_updates) || inplace) {
526                         finish_transfer(fname, fnametmp, file, recv_ok, 1);
527                         if (partialptr != fname && fnamecmp == partialptr) {
528                                 do_unlink(partialptr);
529                                 handle_partial_dir(partialptr, PDIR_DELETE);
530                         }
531                 } else if (keep_partial && partialptr
532                     && handle_partial_dir(partialptr, PDIR_CREATE)) {
533                         finish_transfer(partialptr, fnametmp, file, recv_ok,
534                                         !partial_dir);
535                         if (delay_updates && recv_ok)
536                                 delayed_bits[i/8] |= 1 << (i % 8);
537                 } else {
538                         partialptr = NULL;
539                         do_unlink(fnametmp);
540                 }
541
542                 cleanup_disable();
543
544                 if (!recv_ok) {
545                         int msgtype = csum_length == SUM_LENGTH || read_batch ?
546                                 FERROR : FINFO;
547                         if (msgtype == FERROR || verbose) {
548                                 char *errstr, *redostr, *keptstr;
549                                 if (!(keep_partial && partialptr) && !inplace)
550                                         keptstr = "discarded";
551                                 else if (partial_dir)
552                                         keptstr = "put into partial-dir";
553                                 else
554                                         keptstr = "retained";
555                                 if (msgtype == FERROR) {
556                                         errstr = "ERROR";
557                                         redostr = "";
558                                 } else {
559                                         errstr = "WARNING";
560                                         redostr = " (will try again)";
561                                 }
562                                 rprintf(msgtype,
563                                         "%s: %s failed verification -- update %s%s.\n",
564                                         errstr, safe_fname(fname),
565                                         keptstr, redostr);
566                         }
567                         if (csum_length != SUM_LENGTH) {
568                                 char buf[4];
569                                 SIVAL(buf, 0, i);
570                                 send_msg(MSG_REDO, buf, 4);
571                         }
572                 }
573         }
574         make_backups = save_make_backups;
575
576         if (delay_updates) {
577                 for (i = 0; i < flist->count; i++) {
578                         struct file_struct *file = flist->files[i];
579                         if (!file->basename
580                          || !(delayed_bits[i/8] & (1 << (i % 8))))
581                                 continue;
582                         fname = local_name ? local_name : f_name(file);
583                         partialptr = partial_dir_fname(fname);
584                         if (partialptr) {
585                                 if (make_backups && !make_backup(fname))
586                                         continue;
587                                 if (verbose > 2) {
588                                         rprintf(FINFO, "renaming %s to %s\n",
589                                                 partialptr, fname);
590                                 }
591                                 if (do_rename(partialptr, fname) < 0) {
592                                         rsyserr(FERROR, errno,
593                                                 "rename failed for %s (from %s)",
594                                                 fname, partialptr);
595                                 } else {
596                                         handle_partial_dir(partialptr,
597                                                            PDIR_DELETE);
598                                 }
599                         }
600                 }
601         }
602
603         if (delete_after && !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 }