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