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