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