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