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