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