Merged in the security fixes from 2.5.7.
[rsync/rsync.git] / flist.c
1 /*
2    Copyright (C) Andrew Tridgell 1996
3    Copyright (C) Paul Mackerras 1996
4    Copyright (C) 2001, 2002 by Martin Pool <mbp@samba.org>
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 /** @file flist.c
22  * Generate and receive file lists
23  *
24  * @todo Get rid of the string_area optimization.  Efficiently
25  * allocating blocks is the responsibility of the system's malloc
26  * library, not of rsync.
27  *
28  * @sa http://lists.samba.org/pipermail/rsync/2000-June/002351.html
29  *
30  **/
31
32 #include "rsync.h"
33
34 extern struct stats stats;
35
36 extern int verbose;
37 extern int do_progress;
38 extern int am_server;
39 extern int always_checksum;
40
41 extern int cvs_exclude;
42
43 extern int recurse;
44 extern char *files_from;
45 extern int filesfrom_fd;
46
47 extern int one_file_system;
48 extern int make_backups;
49 extern int preserve_links;
50 extern int preserve_hard_links;
51 extern int preserve_perms;
52 extern int preserve_devices;
53 extern int preserve_uid;
54 extern int preserve_gid;
55 extern int preserve_times;
56 extern int relative_paths;
57 extern int implied_dirs;
58 extern int copy_links;
59 extern int copy_unsafe_links;
60 extern int protocol_version;
61 extern int io_error;
62 extern int sanitize_paths;
63
64 extern int read_batch;
65 extern int write_batch;
66
67 extern struct exclude_struct **exclude_list;
68 extern struct exclude_struct **server_exclude_list;
69 extern struct exclude_struct **local_exclude_list;
70
71 static struct file_struct null_file;
72
73 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
74
75
76 static int show_filelist_p(void)
77 {
78         return verbose && (recurse || files_from) && !am_server;
79 }
80
81 static void start_filelist_progress(char *kind)
82 {
83         rprintf(FINFO, "%s ... ", kind);
84         if ((verbose > 1) || do_progress)
85                 rprintf(FINFO, "\n");
86         rflush(FINFO);
87 }
88
89
90 static void emit_filelist_progress(const struct file_list *flist)
91 {
92         rprintf(FINFO, " %d files...\r", flist->count);
93 }
94
95
96 static void maybe_emit_filelist_progress(const struct file_list *flist)
97 {
98         if (do_progress && show_filelist_p() && ((flist->count % 100) == 0))
99                 emit_filelist_progress(flist);
100 }
101
102
103 static void finish_filelist_progress(const struct file_list *flist)
104 {
105         if (do_progress) {
106                 /* This overwrites the progress line */
107                 rprintf(FINFO, "%d file%sto consider\n",
108                         flist->count, flist->count == 1 ? " " : "s ");
109         } else {
110                 rprintf(FINFO, "done\n");
111         }
112 }
113
114 void show_flist_stats(void)
115 {
116         /* Nothing yet */
117 }
118
119
120 static struct string_area *string_area_new(int size)
121 {
122         struct string_area *a;
123
124         if (size <= 0)
125                 size = ARENA_SIZE;
126         a = new(struct string_area);
127         if (!a)
128                 out_of_memory("string_area_new");
129         a->current = a->base = new_array(char, size);
130         if (!a->current)
131                 out_of_memory("string_area_new buffer");
132         a->end = a->base + size;
133         a->next = NULL;
134
135         return a;
136 }
137
138 static void string_area_free(struct string_area *a)
139 {
140         struct string_area *next;
141
142         for (; a; a = next) {
143                 next = a->next;
144                 free(a->base);
145         }
146 }
147
148 static char *string_area_malloc(struct string_area **ap, int size)
149 {
150         char *p;
151         struct string_area *a;
152
153         /* does the request fit into the current space? */
154         a = *ap;
155         if (a->current + size >= a->end) {
156                 /* no; get space, move new string_area to front of the list */
157                 a = string_area_new(size > ARENA_SIZE ? size : ARENA_SIZE);
158                 a->next = *ap;
159                 *ap = a;
160         }
161
162         /* have space; do the "allocation." */
163         p = a->current;
164         a->current += size;
165         return p;
166 }
167
168 static char *string_area_strdup(struct string_area **ap, const char *src)
169 {
170         char *dest = string_area_malloc(ap, strlen(src) + 1);
171         return strcpy(dest, src);
172 }
173
174 static void list_file_entry(struct file_struct *f)
175 {
176         char perms[11];
177
178         if (!f->basename)
179                 /* this can happen if duplicate names were removed */
180                 return;
181
182         permstring(perms, f->mode);
183
184         if (preserve_links && S_ISLNK(f->mode)) {
185                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
186                         perms,
187                         (double) f->length, timestring(f->modtime),
188                         f_name(f), f->link);
189         } else {
190                 rprintf(FINFO, "%s %11.0f %s %s\n",
191                         perms,
192                         (double) f->length, timestring(f->modtime),
193                         f_name(f));
194         }
195 }
196
197
198 /**
199  * Stat either a symlink or its referent, depending on the settings of
200  * copy_links, copy_unsafe_links, etc.
201  *
202  * @retval -1 on error
203  *
204  * @retval 0 for success
205  *
206  * @post If @p path is a symlink, then @p linkbuf (of size @c
207  * MAXPATHLEN) contains the symlink target.
208  *
209  * @post @p buffer contains information about the link or the
210  * referrent as appropriate, if they exist.
211  **/
212 int readlink_stat(const char *path, STRUCT_STAT * buffer, char *linkbuf)
213 {
214 #if SUPPORT_LINKS
215         if (copy_links) {
216                 return do_stat(path, buffer);
217         }
218         if (do_lstat(path, buffer) == -1) {
219                 return -1;
220         }
221         if (S_ISLNK(buffer->st_mode)) {
222                 int l;
223                 l = readlink((char *) path, linkbuf, MAXPATHLEN - 1);
224                 if (l == -1)
225                         return -1;
226                 linkbuf[l] = 0;
227                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
228                         if (verbose > 1) {
229                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
230                                         path, linkbuf);
231                         }
232                         return do_stat(path, buffer);
233                 }
234         }
235         return 0;
236 #else
237         return do_stat(path, buffer);
238 #endif
239 }
240
241 int link_stat(const char *path, STRUCT_STAT * buffer)
242 {
243 #if SUPPORT_LINKS
244         if (copy_links) {
245                 return do_stat(path, buffer);
246         } else {
247                 return do_lstat(path, buffer);
248         }
249 #else
250         return do_stat(path, buffer);
251 #endif
252 }
253
254 /*
255  * This function is used to check if a file should be included/excluded
256  * from the list of files based on its name and type etc.  The value of
257  * exclude_level is set to either SERVER_EXCLUDES or ALL_EXCLUDES.
258  */
259 static int check_exclude_file(char *fname, int is_dir, int exclude_level)
260 {
261 #if 0 /* This currently never happens, so avoid a useless compare. */
262         if (exclude_level == NO_EXCLUDES)
263                 return 0;
264 #endif
265         if (fname) {
266                 /* never exclude '.', even if somebody does --exclude '*' */
267                 if (fname[0] == '.' && !fname[1])
268                         return 0;
269                 /* Handle the -R version of the '.' dir. */
270                 if (fname[0] == '/') {
271                         int len = strlen(fname);
272                         if (fname[len-1] == '.' && fname[len-2] == '/')
273                                 return 0;
274                 }
275         }
276         if (server_exclude_list
277          && check_exclude(server_exclude_list, fname, is_dir))
278                 return 1;
279         if (exclude_level != ALL_EXCLUDES)
280                 return 0;
281         if (exclude_list && check_exclude(exclude_list, fname, is_dir))
282                 return 1;
283         if (local_exclude_list
284          && check_exclude(local_exclude_list, fname, is_dir))
285                 return 1;
286         return 0;
287 }
288
289 /* used by the one_file_system code */
290 static dev_t filesystem_dev;
291
292 static void set_filesystem(char *fname)
293 {
294         STRUCT_STAT st;
295         if (link_stat(fname, &st) != 0)
296                 return;
297         filesystem_dev = st.st_dev;
298 }
299
300
301 static int to_wire_mode(mode_t mode)
302 {
303         if (S_ISLNK(mode) && (_S_IFLNK != 0120000)) {
304                 return (mode & ~(_S_IFMT)) | 0120000;
305         }
306         return (int) mode;
307 }
308
309 static mode_t from_wire_mode(int mode)
310 {
311         if ((mode & (_S_IFMT)) == 0120000 && (_S_IFLNK != 0120000)) {
312                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
313         }
314         return (mode_t) mode;
315 }
316
317
318 static void send_directory(int f, struct file_list *flist, char *dir);
319
320 static char *flist_dir;
321
322
323 /**
324  * Make sure @p flist is big enough to hold at least @p flist->count
325  * entries.
326  **/
327 static void flist_expand(struct file_list *flist)
328 {
329         if (flist->count >= flist->malloced) {
330                 void *new_ptr;
331
332                 if (flist->malloced < 1000)
333                         flist->malloced += 1000;
334                 else
335                         flist->malloced *= 2;
336
337                 if (flist->files) {
338                         new_ptr = realloc_array(flist->files,
339                                                 struct file_struct *,
340                                                 flist->malloced);
341                 } else {
342                         new_ptr = new_array(struct file_struct *,
343                                             flist->malloced);
344                 }
345
346                 if (verbose >= 2) {
347                         rprintf(FINFO, "expand file_list to %.0f bytes, did%s move\n",
348                                 (double)sizeof(flist->files[0])
349                                 * flist->malloced,
350                                 (new_ptr == flist->files) ? " not" : "");
351                 }
352
353                 flist->files = (struct file_struct **) new_ptr;
354
355                 if (!flist->files)
356                         out_of_memory("flist_expand");
357         }
358 }
359
360
361 static void send_file_entry(struct file_struct *file, int f,
362                             unsigned base_flags)
363 {
364         unsigned char flags;
365         static time_t last_time;
366         static mode_t last_mode;
367         static DEV64_T last_rdev;
368         static uid_t last_uid;
369         static gid_t last_gid;
370         static char lastname[MAXPATHLEN];
371         char *fname;
372         int l1, l2;
373
374         if (f == -1)
375                 return;
376
377         if (!file) {
378                 write_byte(f, 0);
379                 return;
380         }
381
382         io_write_phase = "send_file_entry";
383
384         fname = f_name(file);
385
386         flags = base_flags;
387
388         if (file->mode == last_mode)
389                 flags |= SAME_MODE;
390         if (file->rdev == last_rdev)
391                 flags |= SAME_RDEV;
392         if (file->uid == last_uid)
393                 flags |= SAME_UID;
394         if (file->gid == last_gid)
395                 flags |= SAME_GID;
396         if (file->modtime == last_time)
397                 flags |= SAME_TIME;
398
399         for (l1 = 0;
400              lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
401              l1++) {}
402         l2 = strlen(fname) - l1;
403
404         if (l1 > 0)
405                 flags |= SAME_NAME;
406         if (l2 > 255)
407                 flags |= LONG_NAME;
408
409         /* we must make sure we don't send a zero flags byte or the other
410            end will terminate the flist transfer */
411         if (flags == 0 && !S_ISDIR(file->mode))
412                 flags |= FLAG_DELETE;
413         if (flags == 0)
414                 flags |= LONG_NAME;
415
416         write_byte(f, flags);
417         if (flags & SAME_NAME)
418                 write_byte(f, l1);
419         if (flags & LONG_NAME)
420                 write_int(f, l2);
421         else
422                 write_byte(f, l2);
423         write_buf(f, fname + l1, l2);
424
425         write_longint(f, file->length);
426         if (!(flags & SAME_TIME))
427                 write_int(f, (int) file->modtime);
428         if (!(flags & SAME_MODE))
429                 write_int(f, to_wire_mode(file->mode));
430         if (preserve_uid && !(flags & SAME_UID)) {
431                 add_uid(file->uid);
432                 write_int(f, (int) file->uid);
433         }
434         if (preserve_gid && !(flags & SAME_GID)) {
435                 add_gid(file->gid);
436                 write_int(f, (int) file->gid);
437         }
438         if (preserve_devices && IS_DEVICE(file->mode)
439             && !(flags & SAME_RDEV))
440                 write_int(f, (int) file->rdev);
441
442 #if SUPPORT_LINKS
443         if (preserve_links && S_ISLNK(file->mode)) {
444                 write_int(f, strlen(file->link));
445                 write_buf(f, file->link, strlen(file->link));
446         }
447 #endif
448
449 #if SUPPORT_HARD_LINKS
450         if (preserve_hard_links && S_ISREG(file->mode)) {
451                 if (protocol_version < 26) {
452                         /* 32-bit dev_t and ino_t */
453                         write_int(f, (int) file->dev);
454                         write_int(f, (int) file->inode);
455                 } else {
456                         /* 64-bit dev_t and ino_t */
457                         write_longint(f, file->dev);
458                         write_longint(f, file->inode);
459                 }
460         }
461 #endif
462
463         if (always_checksum) {
464                 if (protocol_version < 21) {
465                         write_buf(f, file->sum, 2);
466                 } else {
467                         write_buf(f, file->sum, MD4_SUM_LENGTH);
468                 }
469         }
470
471         last_mode = file->mode;
472         last_rdev = file->rdev;
473         last_uid = file->uid;
474         last_gid = file->gid;
475         last_time = file->modtime;
476
477         strlcpy(lastname, fname, MAXPATHLEN);
478         lastname[MAXPATHLEN - 1] = 0;
479
480         io_write_phase = "unknown";
481 }
482
483
484
485 static void receive_file_entry(struct file_struct **fptr,
486                                unsigned flags, int f)
487 {
488         static time_t last_time;
489         static mode_t last_mode;
490         static DEV64_T last_rdev;
491         static uid_t last_uid;
492         static gid_t last_gid;
493         static char lastname[MAXPATHLEN];
494         char thisname[MAXPATHLEN];
495         unsigned int l1 = 0, l2 = 0;
496         char *p;
497         struct file_struct *file;
498
499         if (flags & SAME_NAME)
500                 l1 = read_byte(f);
501
502         if (flags & LONG_NAME)
503                 l2 = read_int(f);
504         else
505                 l2 = read_byte(f);
506
507         file = new(struct file_struct);
508         if (!file)
509                 out_of_memory("receive_file_entry");
510         memset((char *) file, 0, sizeof(*file));
511         (*fptr) = file;
512
513         if (l2 >= MAXPATHLEN - l1) {
514                 rprintf(FERROR,
515                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s\n",
516                         flags, l1, l2, lastname);
517                 overflow("receive_file_entry");
518         }
519
520         strlcpy(thisname, lastname, l1 + 1);
521         read_sbuf(f, &thisname[l1], l2);
522         thisname[l1 + l2] = 0;
523
524         strlcpy(lastname, thisname, MAXPATHLEN);
525         lastname[MAXPATHLEN - 1] = 0;
526
527         clean_fname(thisname);
528
529         if (sanitize_paths) {
530                 sanitize_path(thisname, NULL);
531         }
532
533         if ((p = strrchr(thisname, '/'))) {
534                 static char *lastdir;
535                 *p = 0;
536                 if (lastdir && strcmp(thisname, lastdir) == 0) {
537                         file->dirname = lastdir;
538                 } else {
539                         file->dirname = strdup(thisname);
540                         lastdir = file->dirname;
541                 }
542                 file->basename = strdup(p + 1);
543         } else {
544                 file->dirname = NULL;
545                 file->basename = strdup(thisname);
546         }
547
548         if (!file->basename)
549                 out_of_memory("receive_file_entry 1");
550
551
552         file->flags = flags;
553         file->length = read_longint(f);
554         file->modtime =
555             (flags & SAME_TIME) ? last_time : (time_t) read_int(f);
556         file->mode =
557             (flags & SAME_MODE) ? last_mode : from_wire_mode(read_int(f));
558         if (preserve_uid)
559                 file->uid =
560                     (flags & SAME_UID) ? last_uid : (uid_t) read_int(f);
561         if (preserve_gid)
562                 file->gid =
563                     (flags & SAME_GID) ? last_gid : (gid_t) read_int(f);
564         if (preserve_devices && IS_DEVICE(file->mode))
565                 file->rdev =
566                     (flags & SAME_RDEV) ? last_rdev : (DEV64_T) read_int(f);
567
568         if (preserve_links && S_ISLNK(file->mode)) {
569                 int l = read_int(f);
570                 if (l < 0) {
571                         rprintf(FERROR, "overflow: l=%d\n", l);
572                         overflow("receive_file_entry");
573                 }
574                 file->link = new_array(char, l + 1);
575                 if (!file->link)
576                         out_of_memory("receive_file_entry 2");
577                 read_sbuf(f, file->link, l);
578                 if (sanitize_paths) {
579                         sanitize_path(file->link, file->dirname);
580                 }
581         }
582 #if SUPPORT_HARD_LINKS
583         if (preserve_hard_links && S_ISREG(file->mode)) {
584                 if (protocol_version < 26) {
585                         file->dev = read_int(f);
586                         file->inode = read_int(f);
587                 } else {
588                         file->dev = read_longint(f);
589                         file->inode = read_longint(f);
590                 }
591         }
592 #endif
593
594         if (always_checksum) {
595                 file->sum = new_array(char, MD4_SUM_LENGTH);
596                 if (!file->sum)
597                         out_of_memory("md4 sum");
598                 if (protocol_version < 21) {
599                         read_buf(f, file->sum, 2);
600                 } else {
601                         read_buf(f, file->sum, MD4_SUM_LENGTH);
602                 }
603         }
604
605         last_mode = file->mode;
606         last_rdev = file->rdev;
607         last_uid = file->uid;
608         last_gid = file->gid;
609         last_time = file->modtime;
610
611         if (!preserve_perms) {
612                 extern int orig_umask;
613                 /* set an appropriate set of permissions based on original
614                    permissions and umask. This emulates what GNU cp does */
615                 file->mode &= ~orig_umask;
616         }
617 }
618
619
620 /* determine if a file in a different filesstem should be skipped
621    when one_file_system is set. We bascally only want to include
622    the mount points - but they can be hard to find! */
623 static int skip_filesystem(char *fname, STRUCT_STAT * st)
624 {
625         STRUCT_STAT st2;
626         char *p = strrchr(fname, '/');
627
628         /* skip all but directories */
629         if (!S_ISDIR(st->st_mode))
630                 return 1;
631
632         /* if its not a subdirectory then allow */
633         if (!p)
634                 return 0;
635
636         *p = 0;
637         if (link_stat(fname, &st2)) {
638                 *p = '/';
639                 return 0;
640         }
641         *p = '/';
642
643         return (st2.st_dev != filesystem_dev);
644 }
645
646 #define STRDUP(ap, p)   (ap ? string_area_strdup(ap, p) : strdup(p))
647 /* IRIX cc cares that the operands to the ternary have the same type. */
648 #define MALLOC(ap, i)   (ap ? (void*) string_area_malloc(ap, i) : malloc(i))
649
650 /**
651  * Create a file_struct for a named file by reading its stat()
652  * information and performing extensive checks against global
653  * options.
654  *
655  * @return the new file, or NULL if there was an error or this file
656  * should be excluded.
657  *
658  * @todo There is a small optimization opportunity here to avoid
659  * stat()ing the file in some circumstances, which has a certain cost.
660  * We are called immediately after doing readdir(), and so we may
661  * already know the d_type of the file.  We could for example avoid
662  * statting directories if we're not recursing, but this is not a very
663  * important case.  Some systems may not have d_type.
664  **/
665 struct file_struct *make_file(char *fname, struct string_area **ap,
666                               int exclude_level)
667 {
668         struct file_struct *file;
669         STRUCT_STAT st;
670         char sum[SUM_LENGTH];
671         char *p;
672         char cleaned_name[MAXPATHLEN];
673         char linkbuf[MAXPATHLEN];
674         extern int module_id;
675
676         strlcpy(cleaned_name, fname, MAXPATHLEN);
677         cleaned_name[MAXPATHLEN - 1] = 0;
678         clean_fname(cleaned_name);
679         if (sanitize_paths) {
680                 sanitize_path(cleaned_name, NULL);
681         }
682         fname = cleaned_name;
683
684         memset(sum, 0, SUM_LENGTH);
685
686         if (readlink_stat(fname, &st, linkbuf) != 0) {
687                 int save_errno = errno;
688                 if (errno == ENOENT && exclude_level != NO_EXCLUDES) {
689                         /* either symlink pointing nowhere or file that
690                          * was removed during rsync run; see if excluded
691                          * before reporting an error */
692                         if (check_exclude_file(fname, 0, exclude_level)) {
693                                 /* file is excluded anyway, ignore silently */
694                                 return NULL;
695                         }
696                 }
697                 io_error = 1;
698                 rprintf(FERROR, "readlink %s failed: %s\n",
699                         full_fname(fname), strerror(save_errno));
700                 return NULL;
701         }
702
703         /* backup.c calls us with exclude_level set to NO_EXCLUDES. */
704         if (exclude_level == NO_EXCLUDES)
705                 goto skip_excludes;
706
707         if (S_ISDIR(st.st_mode) && !recurse && !files_from) {
708                 rprintf(FINFO, "skipping directory %s\n", fname);
709                 return NULL;
710         }
711
712         if (one_file_system && st.st_dev != filesystem_dev) {
713                 if (skip_filesystem(fname, &st))
714                         return NULL;
715         }
716
717         if (check_exclude_file(fname, S_ISDIR(st.st_mode) != 0, exclude_level))
718                 return NULL;
719
720         if (lp_ignore_nonreadable(module_id) && access(fname, R_OK) != 0)
721                 return NULL;
722
723       skip_excludes:
724
725         if (verbose > 2)
726                 rprintf(FINFO, "make_file(%s,*,%d)\n", fname, exclude_level);
727
728         file = new(struct file_struct);
729         if (!file)
730                 out_of_memory("make_file");
731         memset((char *) file, 0, sizeof(*file));
732
733         if ((p = strrchr(fname, '/'))) {
734                 static char *lastdir;
735                 *p = 0;
736                 if (lastdir && strcmp(fname, lastdir) == 0) {
737                         file->dirname = lastdir;
738                 } else {
739                         file->dirname = strdup(fname);
740                         lastdir = file->dirname;
741                 }
742                 file->basename = STRDUP(ap, p + 1);
743                 *p = '/';
744         } else {
745                 file->dirname = NULL;
746                 file->basename = STRDUP(ap, fname);
747         }
748
749         file->modtime = st.st_mtime;
750         file->length = st.st_size;
751         file->mode = st.st_mode;
752         file->uid = st.st_uid;
753         file->gid = st.st_gid;
754         file->dev = st.st_dev;
755         file->inode = st.st_ino;
756 #ifdef HAVE_STRUCT_STAT_ST_RDEV
757         file->rdev = st.st_rdev;
758 #endif
759
760 #if SUPPORT_LINKS
761         if (S_ISLNK(st.st_mode)) {
762                 file->link = STRDUP(ap, linkbuf);
763         }
764 #endif
765
766         if (always_checksum) {
767                 file->sum = (char *) MALLOC(ap, MD4_SUM_LENGTH);
768                 if (!file->sum)
769                         out_of_memory("md4 sum");
770                 /* drat. we have to provide a null checksum for non-regular
771                    files in order to be compatible with earlier versions
772                    of rsync */
773                 if (S_ISREG(st.st_mode)) {
774                         file_checksum(fname, file->sum, st.st_size);
775                 } else {
776                         memset(file->sum, 0, MD4_SUM_LENGTH);
777                 }
778         }
779
780         if (flist_dir) {
781                 static char *lastdir;
782                 if (lastdir && strcmp(lastdir, flist_dir) == 0) {
783                         file->basedir = lastdir;
784                 } else {
785                         file->basedir = strdup(flist_dir);
786                         lastdir = file->basedir;
787                 }
788         } else {
789                 file->basedir = NULL;
790         }
791
792         if (!S_ISDIR(st.st_mode))
793                 stats.total_size += st.st_size;
794
795         return file;
796 }
797
798
799
800 void send_file_name(int f, struct file_list *flist, char *fname,
801                     int recursive, unsigned base_flags)
802 {
803         struct file_struct *file;
804         extern int delete_excluded;
805
806         /* f is set to -1 when calculating deletion file list */
807         file = make_file(fname, &flist->string_area,
808                          f == -1 && delete_excluded? SERVER_EXCLUDES
809                                                    : ALL_EXCLUDES);
810
811         if (!file)
812                 return;
813
814         maybe_emit_filelist_progress(flist);
815
816         flist_expand(flist);
817
818         if (write_batch)        /*  dw  */
819                 file->flags = FLAG_DELETE;
820
821         if (file->basename[0]) {
822                 flist->files[flist->count++] = file;
823                 send_file_entry(file, f, base_flags);
824         }
825
826         if (S_ISDIR(file->mode) && recursive) {
827                 struct exclude_struct **last_exclude_list =
828                     local_exclude_list;
829                 send_directory(f, flist, f_name(file));
830                 local_exclude_list = last_exclude_list;
831                 return;
832         }
833 }
834
835
836
837 static void send_directory(int f, struct file_list *flist, char *dir)
838 {
839         DIR *d;
840         struct dirent *di;
841         char fname[MAXPATHLEN];
842         int l;
843         char *p;
844
845         d = opendir(dir);
846         if (!d) {
847                 io_error = 1;
848                 rprintf(FERROR, "opendir %s failed: %s\n",
849                         full_fname(dir), strerror(errno));
850                 return;
851         }
852
853         strlcpy(fname, dir, MAXPATHLEN);
854         l = strlen(fname);
855         if (fname[l - 1] != '/') {
856                 if (l == MAXPATHLEN - 1) {
857                         io_error = 1;
858                         rprintf(FERROR, "skipping long-named directory: %s\n",
859                                 full_fname(fname));
860                         closedir(d);
861                         return;
862                 }
863                 strlcat(fname, "/", MAXPATHLEN);
864                 l++;
865         }
866         p = fname + strlen(fname);
867
868         local_exclude_list = NULL;
869
870         if (cvs_exclude) {
871                 if (strlen(fname) + strlen(".cvsignore") <= MAXPATHLEN - 1) {
872                         strcpy(p, ".cvsignore");
873                         add_exclude_file(&exclude_list,fname,MISSING_OK,ADD_EXCLUDE);
874                 } else {
875                         io_error = 1;
876                         rprintf(FINFO,
877                                 "cannot cvs-exclude in long-named directory %s\n",
878                                 full_fname(fname));
879                 }
880         }
881
882         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
883                 char *dname = d_name(di);
884                 if (dname[0] == '.' && (dname[1] == '\0'
885                     || (dname[1] == '.' && dname[2] == '\0')))
886                         continue;
887                 strlcpy(p, dname, MAXPATHLEN - l);
888                 send_file_name(f, flist, fname, recurse, 0);
889         }
890         if (errno) {
891                 io_error = 1;
892                 rprintf(FERROR, "readdir(%s): (%d) %s\n",
893                     dir, errno, strerror(errno));
894         }
895
896         if (local_exclude_list)
897                 free_exclude_list(&local_exclude_list); /* Zeros pointer too */
898
899         closedir(d);
900 }
901
902
903 /**
904  * The delete_files() function in receiver.c sets f to -1 so that we just
905  * construct the file list in memory without sending it over the wire.  It
906  * also has the side-effect of ignoring user-excludes if delete_excluded
907  * is set (so that the delete list includes user-excluded files).
908  **/
909 struct file_list *send_file_list(int f, int argc, char *argv[])
910 {
911         int l;
912         STRUCT_STAT st;
913         char *p, *dir, *olddir;
914         char lastpath[MAXPATHLEN] = "";
915         struct file_list *flist;
916         int64 start_write;
917         int use_ff_fd = 0;
918
919         if (show_filelist_p() && f != -1)
920                 start_filelist_progress("building file list");
921
922         start_write = stats.total_written;
923
924         flist = flist_new();
925
926         if (f != -1) {
927                 io_start_buffering(f);
928                 if (filesfrom_fd >= 0) {
929                         if (argv[0] && !push_dir(argv[0], 0)) {
930                                 rprintf(FERROR, "push_dir %s failed: %s\n",
931                                         full_fname(argv[0]), strerror(errno));
932                                 exit_cleanup(RERR_FILESELECT);
933                         }
934                         use_ff_fd = 1;
935                 }
936         }
937
938         while (1) {
939                 char fname2[MAXPATHLEN];
940                 char *fname = fname2;
941
942                 if (use_ff_fd) {
943                         if (read_filesfrom_line(filesfrom_fd, fname) == 0)
944                                 break;
945                         sanitize_path(fname, NULL);
946                 } else {
947                         if (argc-- == 0)
948                                 break;
949                         strlcpy(fname, *argv++, MAXPATHLEN);
950                         if (sanitize_paths)
951                                 sanitize_path(fname, NULL);
952                 }
953
954                 l = strlen(fname);
955                 if (fname[l - 1] == '/') {
956                         if (l == 2 && fname[0] == '.') {
957                                 /* Turn "./" into just "." rather than "./." */
958                                 fname[1] = '\0';
959                         } else {
960                                 strlcat(fname, ".", MAXPATHLEN);
961                         }
962                 }
963
964                 if (link_stat(fname, &st) != 0) {
965                         if (f != -1) {
966                                 io_error = 1;
967                                 rprintf(FERROR, "link_stat %s failed: %s\n",
968                                         full_fname(fname), strerror(errno));
969                         }
970                         continue;
971                 }
972
973                 if (S_ISDIR(st.st_mode) && !recurse && !files_from) {
974                         rprintf(FINFO, "skipping directory %s\n", fname);
975                         continue;
976                 }
977
978                 dir = NULL;
979                 olddir = NULL;
980
981                 if (!relative_paths) {
982                         p = strrchr(fname, '/');
983                         if (p) {
984                                 *p = 0;
985                                 if (p == fname)
986                                         dir = "/";
987                                 else
988                                         dir = fname;
989                                 fname = p + 1;
990                         }
991                 } else if (f != -1 && implied_dirs && (p=strrchr(fname,'/')) && p != fname) {
992                         /* this ensures we send the intermediate directories,
993                            thus getting their permissions right */
994                         char *lp = lastpath, *fn = fname, *slash = fname;
995                         *p = 0;
996                         /* Skip any initial directories in our path that we
997                          * have in common with lastpath. */
998                         while (*fn && *lp == *fn) {
999                                 if (*fn == '/')
1000                                         slash = fn;
1001                                 lp++, fn++;
1002                         }
1003                         *p = '/';
1004                         if (fn != p || (*lp && *lp != '/')) {
1005                                 int copy_links_saved = copy_links;
1006                                 int recurse_saved = recurse;
1007                                 copy_links = copy_unsafe_links;
1008                                 /* set recurse to 1 to prevent make_file
1009                                  * from ignoring directory, but still
1010                                  * turn off the recursive parameter to
1011                                  * send_file_name */
1012                                 recurse = 1;
1013                                 while ((slash = strchr(slash+1, '/')) != 0) {
1014                                         *slash = 0;
1015                                         send_file_name(f, flist, fname, 0, 0);
1016                                         *slash = '/';
1017                                 }
1018                                 copy_links = copy_links_saved;
1019                                 recurse = recurse_saved;
1020                                 *p = 0;
1021                                 strlcpy(lastpath, fname, sizeof lastpath);
1022                                 *p = '/';
1023                         }
1024                 }
1025
1026                 if (!*fname)
1027                         fname = ".";
1028
1029                 if (dir && *dir) {
1030                         olddir = push_dir(dir, 1);
1031
1032                         if (!olddir) {
1033                                 io_error = 1;
1034                                 rprintf(FERROR, "push_dir %s failed: %s\n",
1035                                         full_fname(dir), strerror(errno));
1036                                 continue;
1037                         }
1038
1039                         flist_dir = dir;
1040                 }
1041
1042                 if (one_file_system)
1043                         set_filesystem(fname);
1044
1045                 send_file_name(f, flist, fname, recurse, FLAG_DELETE);
1046
1047                 if (olddir != NULL) {
1048                         flist_dir = NULL;
1049                         if (pop_dir(olddir) != 0) {
1050                                 rprintf(FERROR, "pop_dir %s failed: %s\n",
1051                                         full_fname(dir), strerror(errno));
1052                                 exit_cleanup(RERR_FILESELECT);
1053                         }
1054                 }
1055         }
1056
1057         if (f != -1) {
1058                 send_file_entry(NULL, f, 0);
1059         }
1060
1061         if (show_filelist_p() && f != -1) {
1062                 finish_filelist_progress(flist);
1063         }
1064
1065         clean_flist(flist, 0, 0);
1066
1067         /* now send the uid/gid list. This was introduced in protocol
1068            version 15 */
1069         if (f != -1) {
1070                 send_uid_list(f);
1071         }
1072
1073         /* send the io_error flag */
1074         if (f != -1) {
1075                 extern int module_id;
1076                 write_int(f, lp_ignore_errors(module_id) ? 0 : io_error);
1077         }
1078
1079         if (f != -1) {
1080                 io_end_buffering();
1081                 stats.flist_size = stats.total_written - start_write;
1082                 stats.num_files = flist->count;
1083                 if (write_batch)        /*  dw  */
1084                         write_batch_flist_info(flist->count, flist->files);
1085         }
1086
1087         if (verbose > 2)
1088                 rprintf(FINFO, "send_file_list done\n");
1089
1090         return flist;
1091 }
1092
1093
1094 struct file_list *recv_file_list(int f)
1095 {
1096         struct file_list *flist;
1097         unsigned char flags;
1098         int64 start_read;
1099         extern int list_only;
1100
1101         if (show_filelist_p())
1102                 start_filelist_progress("receiving file list");
1103
1104         start_read = stats.total_read;
1105
1106         flist = new(struct file_list);
1107         if (!flist)
1108                 goto oom;
1109
1110         flist->count = 0;
1111         flist->malloced = 1000;
1112         flist->files = new_array(struct file_struct *, flist->malloced);
1113         if (!flist->files)
1114                 goto oom;
1115
1116
1117         for (flags = read_byte(f); flags; flags = read_byte(f)) {
1118                 int i = flist->count;
1119
1120                 flist_expand(flist);
1121
1122                 receive_file_entry(&flist->files[i], flags, f);
1123
1124                 if (S_ISREG(flist->files[i]->mode))
1125                         stats.total_size += flist->files[i]->length;
1126
1127                 flist->count++;
1128
1129                 maybe_emit_filelist_progress(flist);
1130
1131                 if (verbose > 2)
1132                         rprintf(FINFO, "recv_file_name(%s)\n",
1133                                 f_name(flist->files[i]));
1134         }
1135
1136
1137         if (verbose > 2)
1138                 rprintf(FINFO, "received %d names\n", flist->count);
1139
1140         clean_flist(flist, relative_paths, 1);
1141
1142         if (show_filelist_p()) {
1143                 finish_filelist_progress(flist);
1144         }
1145
1146         /* now recv the uid/gid list. This was introduced in protocol version 15 */
1147         if (f != -1) {
1148                 recv_uid_list(f, flist);
1149         }
1150
1151         /* recv the io_error flag */
1152         if (f != -1 && !read_batch) {   /* dw-added readbatch */
1153                 extern int module_id;
1154                 extern int ignore_errors;
1155                 if (lp_ignore_errors(module_id) || ignore_errors) {
1156                         read_int(f);
1157                 } else {
1158                         io_error |= read_int(f);
1159                 }
1160         }
1161
1162         if (list_only) {
1163                 int i;
1164                 for (i = 0; i < flist->count; i++) {
1165                         list_file_entry(flist->files[i]);
1166                 }
1167         }
1168
1169
1170         if (verbose > 2)
1171                 rprintf(FINFO, "recv_file_list done\n");
1172
1173         stats.flist_size = stats.total_read - start_read;
1174         stats.num_files = flist->count;
1175
1176         return flist;
1177
1178       oom:
1179         out_of_memory("recv_file_list");
1180         return NULL;            /* not reached */
1181 }
1182
1183
1184 /*
1185  * XXX: This is currently the hottest function while building the file
1186  * list, because building f_name()s every time is expensive.
1187  **/
1188 int file_compare(struct file_struct **f1, struct file_struct **f2)
1189 {
1190         if (!(*f1)->basename && !(*f2)->basename)
1191                 return 0;
1192         if (!(*f1)->basename)
1193                 return -1;
1194         if (!(*f2)->basename)
1195                 return 1;
1196         if ((*f1)->dirname == (*f2)->dirname)
1197                 return u_strcmp((*f1)->basename, (*f2)->basename);
1198         return u_strcmp(f_name(*f1), f_name(*f2));
1199 }
1200
1201
1202 int flist_find(struct file_list *flist, struct file_struct *f)
1203 {
1204         int low = 0, high = flist->count - 1;
1205
1206         while (high >= 0 && !flist->files[high]->basename) high--;
1207
1208         if (high < 0)
1209                 return -1;
1210
1211         while (low != high) {
1212                 int mid = (low + high) / 2;
1213                 int ret =
1214                     file_compare(&flist->files[flist_up(flist, mid)], &f);
1215                 if (ret == 0)
1216                         return flist_up(flist, mid);
1217                 if (ret > 0) {
1218                         high = mid;
1219                 } else {
1220                         low = mid + 1;
1221                 }
1222         }
1223
1224         if (file_compare(&flist->files[flist_up(flist, low)], &f) == 0)
1225                 return flist_up(flist, low);
1226         return -1;
1227 }
1228
1229
1230 /*
1231  * free up one file
1232  */
1233 void free_file(struct file_struct *file)
1234 {
1235         if (!file)
1236                 return;
1237         if (file->basename)
1238                 free(file->basename);
1239         if (file->link)
1240                 free(file->link);
1241         if (file->sum)
1242                 free(file->sum);
1243         *file = null_file;
1244 }
1245
1246
1247 /*
1248  * allocate a new file list
1249  */
1250 struct file_list *flist_new(void)
1251 {
1252         struct file_list *flist;
1253
1254         flist = new(struct file_list);
1255         if (!flist)
1256                 out_of_memory("send_file_list");
1257
1258         flist->count = 0;
1259         flist->malloced = 0;
1260         flist->files = NULL;
1261
1262 #if ARENA_SIZE > 0
1263         flist->string_area = string_area_new(0);
1264 #else
1265         flist->string_area = NULL;
1266 #endif
1267         return flist;
1268 }
1269
1270 /*
1271  * free up all elements in a flist
1272  */
1273 void flist_free(struct file_list *flist)
1274 {
1275         int i;
1276         for (i = 1; i < flist->count; i++) {
1277                 if (!flist->string_area)
1278                         free_file(flist->files[i]);
1279                 free(flist->files[i]);
1280         }
1281         /* FIXME: I don't think we generally need to blank the flist
1282          * since it's about to be freed.  This will just cause more
1283          * memory traffic.  If you want a freed-memory debugger, you
1284          * know where to get it. */
1285         memset((char *) flist->files, 0,
1286                sizeof(flist->files[0]) * flist->count);
1287         free(flist->files);
1288         if (flist->string_area)
1289                 string_area_free(flist->string_area);
1290         memset((char *) flist, 0, sizeof(*flist));
1291         free(flist);
1292 }
1293
1294
1295 /*
1296  * This routine ensures we don't have any duplicate names in our file list.
1297  * duplicate names can cause corruption because of the pipelining
1298  */
1299 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1300 {
1301         int i, prev_i = 0;
1302         char *name, *prev_name = NULL;
1303
1304         if (!flist || flist->count == 0)
1305                 return;
1306
1307         qsort(flist->files, flist->count,
1308               sizeof(flist->files[0]), (int (*)()) file_compare);
1309
1310         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1311                 if (flist->files[i]->basename) {
1312                         prev_i = i;
1313                         prev_name = f_name(flist->files[i]);
1314                         break;
1315                 }
1316         }
1317         while (++i < flist->count) {
1318                 if (!flist->files[i]->basename)
1319                         continue;
1320                 name = f_name(flist->files[i]);
1321                 if (strcmp(name, prev_name) == 0) {
1322                         if (verbose > 1 && !am_server) {
1323                                 rprintf(FINFO,
1324                                         "removing duplicate name %s from file list %d\n",
1325                                         name, i);
1326                         }
1327                         /* Make sure that if we unduplicate '.', that we don't
1328                          * lose track of a user-specified starting point (or
1329                          * else deletions will mysteriously fail with -R). */
1330                         if (flist->files[i]->flags & FLAG_DELETE)
1331                                 flist->files[prev_i]->flags |= FLAG_DELETE;
1332                         /* it's not great that the flist knows the semantics of
1333                          * the file memory usage, but i'd rather not add a flag
1334                          * byte to that struct.
1335                          * XXX can i use a bit in the flags field? */
1336                         if (flist->string_area)
1337                                 flist->files[i][0] = null_file;
1338                         else
1339                                 free_file(flist->files[i]);
1340                 }
1341                 else
1342                         prev_i = i;
1343                 /* We set prev_name every iteration to avoid it becoming
1344                  * invalid when names[][] in f_name() wraps around. */
1345                 prev_name = name;
1346         }
1347
1348         if (strip_root) {
1349                 /* we need to strip off the root directory in the case
1350                    of relative paths, but this must be done _after_
1351                    the sorting phase */
1352                 for (i = 0; i < flist->count; i++) {
1353                         if (flist->files[i]->dirname &&
1354                             flist->files[i]->dirname[0] == '/') {
1355                                 memmove(&flist->files[i]->dirname[0],
1356                                         &flist->files[i]->dirname[1],
1357                                         strlen(flist->files[i]->dirname));
1358                         }
1359
1360                         if (flist->files[i]->dirname &&
1361                             !flist->files[i]->dirname[0]) {
1362                                 flist->files[i]->dirname = NULL;
1363                         }
1364                 }
1365         }
1366
1367         if (verbose <= 3)
1368                 return;
1369
1370         for (i = 0; i < flist->count; i++) {
1371                 rprintf(FINFO, "[%d] i=%d %s %s mode=0%o len=%.0f\n",
1372                         (int) getpid(), i,
1373                         NS(flist->files[i]->dirname),
1374                         NS(flist->files[i]->basename),
1375                         (int) flist->files[i]->mode,
1376                         (double) flist->files[i]->length);
1377         }
1378 }
1379
1380
1381 /*
1382  * return the full filename of a flist entry
1383  *
1384  * This function is too expensive at the moment, because it copies
1385  * strings when often we only want to compare them.  In any case,
1386  * using strlcat is silly because it will walk the string repeatedly.
1387  */
1388 char *f_name(struct file_struct *f)
1389 {
1390         static char names[10][MAXPATHLEN];
1391         static int n;
1392         char *p = names[n];
1393
1394         if (!f || !f->basename)
1395                 return NULL;
1396
1397         n = (n + 1) % 10;
1398
1399         if (f->dirname) {
1400                 int off;
1401
1402                 off = strlcpy(p, f->dirname, MAXPATHLEN);
1403                 off += strlcpy(p + off, "/", MAXPATHLEN - off);
1404                 off += strlcpy(p + off, f->basename, MAXPATHLEN - off);
1405         } else {
1406                 strlcpy(p, f->basename, MAXPATHLEN);
1407         }
1408
1409         return p;
1410 }