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