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