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