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