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