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