Some simple whitespace tweaks.
[rsync/rsync.git] / receiver.c
1 /* -*- c-file-style: "linux" -*-
2
3    Copyright (C) 1996-2000 by Andrew Tridgell
4    Copyright (C) Paul Mackerras 1996
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "rsync.h"
22
23 extern int verbose;
24 extern int recurse;
25 extern int delete_mode;
26 extern int delete_after;
27 extern int max_delete;
28 extern int csum_length;
29 extern struct stats stats;
30 extern int dry_run;
31 extern int am_server;
32 extern int relative_paths;
33 extern int keep_dirlinks;
34 extern int preserve_hard_links;
35 extern int preserve_perms;
36 extern int cvs_exclude;
37 extern int io_error;
38 extern char *tmpdir;
39 extern char *compare_dest;
40 extern int make_backups;
41 extern int do_progress;
42 extern char *backup_dir;
43 extern char *backup_suffix;
44 extern int backup_suffix_len;
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
52 static void delete_one(char *fn, int is_dir)
53 {
54         if (!is_dir) {
55                 if (robust_unlink(fn) != 0) {
56                         rsyserr(FERROR, errno, "delete_one: unlink %s failed",
57                                 full_fname(fn));
58                 } else if (verbose) {
59                         rprintf(FINFO, "deleting %s\n", fn);
60                 }
61         } else {
62                 if (do_rmdir(fn) != 0) {
63                         if (errno == ENOTDIR && keep_dirlinks) {
64                                 delete_one(fn, 0);
65                                 return;
66                         }
67                         if (errno != ENOTEMPTY && errno != EEXIST) {
68                                 rsyserr(FERROR, errno,
69                                         "delete_one: rmdir %s failed",
70                                         full_fname(fn));
71                         }
72                 } else if (verbose) {
73                         rprintf(FINFO, "deleting directory %s\n", fn);
74                 }
75         }
76 }
77
78
79 static int is_backup_file(char *fn)
80 {
81         int k = strlen(fn) - backup_suffix_len;
82         return k > 0 && strcmp(fn+k, backup_suffix) == 0;
83 }
84
85
86 /* This deletes any files on the receiving side that are not present
87  * on the sending side. */
88 void delete_files(struct file_list *flist)
89 {
90         struct file_list *local_file_list;
91         int i, j;
92         char *argv[1], fbuf[MAXPATHLEN];
93         static int deletion_count;
94
95         if (cvs_exclude)
96                 add_cvs_excludes();
97
98         if (io_error && !(lp_ignore_errors(module_id) || ignore_errors)) {
99                 rprintf(FINFO,"IO error encountered - skipping file deletion\n");
100                 return;
101         }
102
103         for (j = 0; j < flist->count; j++) {
104                 if (!(flist->files[j]->flags & FLAG_TOP_DIR)
105                     || !S_ISDIR(flist->files[j]->mode))
106                         continue;
107
108                 argv[0] = f_name_to(flist->files[j], fbuf);
109
110                 if (!(local_file_list = send_file_list(-1, 1, argv)))
111                         continue;
112
113                 if (verbose > 1)
114                         rprintf(FINFO, "deleting in %s\n", fbuf);
115
116                 for (i = local_file_list->count-1; i >= 0; i--) {
117                         if (max_delete && deletion_count > max_delete)
118                                 break;
119                         if (!local_file_list->files[i]->basename)
120                                 continue;
121                         if (flist_find(flist,local_file_list->files[i]) < 0) {
122                                 char *f = f_name(local_file_list->files[i]);
123                                 if (make_backups && (backup_dir || !is_backup_file(f))) {
124                                         (void) make_backup(f);
125                                         if (verbose)
126                                                 rprintf(FINFO, "deleting %s\n", f);
127                                 } else {
128                                         int mode = local_file_list->files[i]->mode;
129                                         delete_one(f, S_ISDIR(mode) != 0);
130                                 }
131                                 deletion_count++;
132                         }
133                 }
134                 flist_free(local_file_list);
135         }
136 }
137
138
139 /*
140  * get_tmpname() - create a tmp filename for a given filename
141  *
142  *   If a tmpdir is defined, use that as the directory to
143  *   put it in.  Otherwise, the tmp filename is in the same
144  *   directory as the given name.  Note that there may be no
145  *   directory at all in the given name!
146  *
147  *   The tmp filename is basically the given filename with a
148  *   dot prepended, and .XXXXXX appended (for mkstemp() to
149  *   put its unique gunk in).  Take care to not exceed
150  *   either the MAXPATHLEN or NAME_MAX, esp. the last, as
151  *   the basename basically becomes 8 chars longer. In that
152  *   case, the original name is shortened sufficiently to
153  *   make it all fit.
154  *
155  *   Of course, there's no real reason for the tmp name to
156  *   look like the original, except to satisfy us humans.
157  *   As long as it's unique, rsync will work.
158  */
159
160 static int get_tmpname(char *fnametmp, char *fname)
161 {
162         char *f;
163         int     length = 0;
164         int     maxname;
165
166         if (tmpdir) {
167                 /* Note: this can't overflow, so the return value is safe */
168                 length = strlcpy(fnametmp, tmpdir, MAXPATHLEN - 2);
169                 fnametmp[length++] = '/';
170                 fnametmp[length] = '\0';        /* always NULL terminated */
171         }
172
173         if ((f = strrchr(fname, '/')) != NULL) {
174                 ++f;
175                 if (!tmpdir) {
176                         length = f - fname;
177                         /* copy up to and including the slash */
178                         strlcpy(fnametmp, fname, length + 1);
179                 }
180         } else
181                 f = fname;
182         fnametmp[length++] = '.';
183         fnametmp[length] = '\0';                /* always NULL terminated */
184
185         maxname = MIN(MAXPATHLEN - 7 - length, NAME_MAX - 8);
186
187         if (maxname < 1) {
188                 rprintf(FERROR, "temporary filename too long: %s\n", fname);
189                 fnametmp[0] = '\0';
190                 return 0;
191         }
192
193         strlcpy(fnametmp + length, f, maxname);
194         strcat(fnametmp + length, ".XXXXXX");
195
196         return 1;
197 }
198
199
200 static int receive_data(int f_in,struct map_struct *mapbuf,int fd,char *fname,
201                         OFF_T total_size)
202 {
203         int i;
204         struct sum_struct sum;
205         unsigned int len;
206         OFF_T offset = 0;
207         OFF_T offset2;
208         char *data;
209         static char file_sum1[MD4_SUM_LENGTH];
210         static char file_sum2[MD4_SUM_LENGTH];
211         char *map = NULL;
212
213         read_sum_head(f_in, &sum);
214
215         sum_init(checksum_seed);
216
217         while ((i = recv_token(f_in, &data)) != 0) {
218                 if (do_progress)
219                         show_progress(offset, total_size);
220
221                 if (i > 0) {
222                         if (verbose > 3) {
223                                 rprintf(FINFO,"data recv %d at %.0f\n",
224                                         i,(double)offset);
225                         }
226
227                         stats.literal_data += i;
228                         cleanup_got_literal = 1;
229
230                         sum_update(data,i);
231
232                         if (fd != -1 && write_file(fd,data,i) != i) {
233                                 rsyserr(FERROR, errno, "write failed on %s",
234                                         full_fname(fname));
235                                 exit_cleanup(RERR_FILEIO);
236                         }
237                         offset += i;
238                         continue;
239                 }
240
241                 i = -(i+1);
242                 offset2 = i*(OFF_T)sum.blength;
243                 len = sum.blength;
244                 if (i == (int) sum.count-1 && sum.remainder != 0)
245                         len = sum.remainder;
246
247                 stats.matched_data += len;
248
249                 if (verbose > 3)
250                         rprintf(FINFO,"chunk[%d] of size %d at %.0f offset=%.0f\n",
251                                 i,len,(double)offset2,(double)offset);
252
253                 if (mapbuf) {
254                         map = map_ptr(mapbuf,offset2,len);
255
256                         see_token(map, len);
257                         sum_update(map,len);
258                 }
259
260                 if (fd != -1 && write_file(fd,map,len) != (int) len) {
261                         rsyserr(FERROR, errno, "write failed on %s",
262                                 full_fname(fname));
263                         exit_cleanup(RERR_FILEIO);
264                 }
265                 offset += len;
266         }
267
268         flush_write_file(fd);
269
270         if (do_progress)
271                 end_progress(total_size);
272
273         if (fd != -1 && offset > 0 && sparse_end(fd) != 0) {
274                 rsyserr(FERROR, errno, "write failed on %s",
275                         full_fname(fname));
276                 exit_cleanup(RERR_FILEIO);
277         }
278
279         sum_end(file_sum1);
280
281         read_buf(f_in,file_sum2,MD4_SUM_LENGTH);
282         if (verbose > 2) {
283                 rprintf(FINFO,"got file_sum\n");
284         }
285         if (fd != -1 && memcmp(file_sum1,file_sum2,MD4_SUM_LENGTH) != 0) {
286                 return 0;
287         }
288         return 1;
289 }
290
291
292 /**
293  * main routine for receiver process.
294  *
295  * Receiver process runs on the same host as the generator process. */
296 int recv_files(int f_in,struct file_list *flist,char *local_name)
297 {
298         int fd1,fd2;
299         STRUCT_STAT st;
300         char *fname, fbuf[MAXPATHLEN];
301         char template[MAXPATHLEN];
302         char fnametmp[MAXPATHLEN];
303         char *fnamecmp;
304         char fnamecmpbuf[MAXPATHLEN];
305         struct map_struct *mapbuf;
306         struct file_struct *file;
307         struct stats initial_stats;
308         int save_make_backups = make_backups;
309         int i, recv_ok, phase = 0;
310
311         if (verbose > 2) {
312                 rprintf(FINFO,"recv_files(%d) starting\n",flist->count);
313         }
314
315         if (flist->hlink_pool) {
316                 pool_destroy(flist->hlink_pool);
317                 flist->hlink_pool = NULL;
318         }
319
320         while (1) {
321                 cleanup_disable();
322
323                 i = read_int(f_in);
324                 if (i == -1) {
325                         if (phase)
326                                 break;
327                         phase = 1;
328                         csum_length = SUM_LENGTH;
329                         if (verbose > 2)
330                                 rprintf(FINFO, "recv_files phase=%d\n", phase);
331                         send_msg(MSG_DONE, "", 0);
332                         if (keep_partial)
333                                 make_backups = 0; /* prevents double backup */
334                         continue;
335                 }
336
337                 if (i < 0 || i >= flist->count) {
338                         rprintf(FERROR,"Invalid file index %d in recv_files (count=%d)\n",
339                                 i, flist->count);
340                         exit_cleanup(RERR_PROTOCOL);
341                 }
342
343                 file = flist->files[i];
344
345                 stats.current_file_index = i;
346                 stats.num_transferred_files++;
347                 stats.total_transferred_size += file->length;
348                 cleanup_got_literal = 0;
349
350                 if (local_name)
351                         fname = local_name;
352                 else
353                         fname = f_name_to(file, fbuf);
354
355                 if (dry_run) {
356                         if (!am_server && verbose) {    /* log transfer */
357                                 rprintf(FINFO, "%s\n", fname);
358                         }
359                         continue;
360                 }
361
362                 initial_stats = stats;
363
364                 if (verbose > 2)
365                         rprintf(FINFO,"recv_files(%s)\n",fname);
366
367                 fnamecmp = fname;
368
369                 /* open the file */
370                 fd1 = do_open(fnamecmp, O_RDONLY, 0);
371
372                 if (fd1 == -1 && compare_dest != NULL) {
373                         /* try the file at compare_dest instead */
374                         pathjoin(fnamecmpbuf, sizeof fnamecmpbuf,
375                                  compare_dest, fname);
376                         fnamecmp = fnamecmpbuf;
377                         fd1 = do_open(fnamecmp, O_RDONLY, 0);
378                 }
379
380                 if (fd1 != -1 && do_fstat(fd1,&st) != 0) {
381                         rsyserr(FERROR, errno, "fstat %s failed",
382                                 full_fname(fnamecmp));
383                         receive_data(f_in,NULL,-1,NULL,file->length);
384                         close(fd1);
385                         continue;
386                 }
387
388                 if (fd1 != -1 && S_ISDIR(st.st_mode) && fnamecmp == fname) {
389                         /* this special handling for directories
390                          * wouldn't be necessary if robust_rename()
391                          * and the underlying robust_unlink could cope
392                          * with directories
393                          */
394                         rprintf(FERROR,"recv_files: %s is a directory\n",
395                                 full_fname(fnamecmp));
396                         receive_data(f_in, NULL, -1, NULL, file->length);
397                         close(fd1);
398                         continue;
399                 }
400
401                 if (fd1 != -1 && !S_ISREG(st.st_mode)) {
402                         close(fd1);
403                         fd1 = -1;
404                         mapbuf = NULL;
405                 }
406
407                 if (fd1 != -1 && !preserve_perms) {
408                         /* if the file exists already and we aren't preserving
409                          * permissions then act as though the remote end sent
410                          * us the file permissions we already have */
411                         file->mode = st.st_mode;
412                 }
413
414                 if (fd1 != -1 && st.st_size > 0) {
415                         mapbuf = map_file(fd1,st.st_size);
416                         if (verbose > 2) {
417                                 rprintf(FINFO, "recv mapped %s of size %.0f\n",
418                                         fnamecmp, (double)st.st_size);
419                         }
420                 } else
421                         mapbuf = NULL;
422
423                 if (!get_tmpname(fnametmp,fname)) {
424                         if (mapbuf) unmap_file(mapbuf);
425                         if (fd1 != -1) close(fd1);
426                         continue;
427                 }
428
429                 strlcpy(template, fnametmp, sizeof template);
430
431                 /* we initially set the perms without the
432                  * setuid/setgid bits to ensure that there is no race
433                  * condition. They are then correctly updated after
434                  * the lchown. Thanks to snabb@epipe.fi for pointing
435                  * this out.  We also set it initially without group
436                  * access because of a similar race condition. */
437                 fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
438
439                 /* in most cases parent directories will already exist
440                  * because their information should have been previously
441                  * transferred, but that may not be the case with -R */
442                 if (fd2 == -1 && relative_paths && errno == ENOENT &&
443                     create_directory_path(fnametmp, orig_umask) == 0) {
444                         strlcpy(fnametmp, template, sizeof fnametmp);
445                         fd2 = do_mkstemp(fnametmp, file->mode & INITACCESSPERMS);
446                 }
447                 if (fd2 == -1) {
448                         rsyserr(FERROR, errno, "mkstemp %s failed",
449                                 full_fname(fnametmp));
450                         receive_data(f_in,mapbuf,-1,NULL,file->length);
451                         if (mapbuf) unmap_file(mapbuf);
452                         if (fd1 != -1) close(fd1);
453                         continue;
454                 }
455
456                 cleanup_set(fnametmp, fname, file, mapbuf, fd1, fd2);
457
458                 if (!am_server && verbose) {    /* log transfer */
459                         rprintf(FINFO, "%s\n", fname);
460                 }
461
462                 /* recv file data */
463                 recv_ok = receive_data(f_in,mapbuf,fd2,fname,file->length);
464
465                 log_recv(file, &initial_stats);
466
467                 if (mapbuf) unmap_file(mapbuf);
468                 if (fd1 != -1) {
469                         close(fd1);
470                 }
471                 if (close(fd2) < 0) {
472                         rsyserr(FERROR, errno, "close failed on %s",
473                                 full_fname(fnametmp));
474                         exit_cleanup(RERR_FILEIO);
475                 }
476
477                 if (verbose > 2)
478                         rprintf(FINFO,"renaming %s to %s\n",fnametmp,fname);
479
480                 if (recv_ok || keep_partial)
481                         finish_transfer(fname, fnametmp, file, recv_ok);
482                 else
483                         do_unlink(fnametmp);
484
485                 cleanup_disable();
486
487                 if (!recv_ok) {
488                         if (csum_length == SUM_LENGTH) {
489                                 rprintf(FERROR,"ERROR: file corruption in %s. File changed during transfer?\n",
490                                         full_fname(fname));
491                         } else {
492                                 char buf[4];
493                                 if (verbose > 1)
494                                         rprintf(FINFO,"redoing %s(%d)\n",fname,i);
495                                 SIVAL(buf, 0, i);
496                                 send_msg(MSG_REDO, buf, 4);
497                         }
498                 }
499         }
500         make_backups = save_make_backups;
501
502         if (delete_after && recurse && delete_mode && !local_name
503             && flist->count > 0)
504                 delete_files(flist);
505
506         if (verbose > 2)
507                 rprintf(FINFO,"recv_files finished\n");
508
509         return 0;
510 }