Optimized flist_find() so that we never scan a series of empty
[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  * @sa http://lists.samba.org/pipermail/rsync/2000-June/002351.html
25  *
26  **/
27
28 #include "rsync.h"
29
30 extern int verbose;
31 extern int dry_run;
32 extern int list_only;
33 extern int am_root;
34 extern int am_server;
35 extern int am_daemon;
36 extern int am_sender;
37 extern int do_progress;
38 extern int always_checksum;
39 extern int module_id;
40 extern int ignore_errors;
41 extern int numeric_ids;
42 extern int recurse;
43 extern int xfer_dirs;
44 extern int filesfrom_fd;
45 extern int one_file_system;
46 extern int keep_dirlinks;
47 extern int preserve_links;
48 extern int preserve_hard_links;
49 extern int preserve_perms;
50 extern int preserve_devices;
51 extern int preserve_specials;
52 extern int preserve_uid;
53 extern int preserve_gid;
54 extern int relative_paths;
55 extern int implied_dirs;
56 extern int skip_empty_dirs;
57 extern int copy_links;
58 extern int copy_unsafe_links;
59 extern int protocol_version;
60 extern int sanitize_paths;
61 extern int orig_umask;
62 extern struct stats stats;
63 extern struct file_list *the_file_list;
64
65 extern char curr_dir[MAXPATHLEN];
66
67 extern struct chmod_mode_struct *chmod_modes;
68
69 extern struct filter_list_struct filter_list;
70 extern struct filter_list_struct server_filter_list;
71
72 int io_error;
73 int checksum_len;
74 dev_t filesystem_dev; /* used to implement -x */
75 unsigned int file_struct_len;
76
77 static char empty_sum[MD4_SUM_LENGTH];
78 static int flist_count_offset;
79 static int max_dir_depth = 0;
80
81 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
82 static void output_flist(struct file_list *flist);
83
84 void init_flist(void)
85 {
86         struct file_struct f;
87
88         /* Figure out how big the file_struct is without trailing padding */
89         file_struct_len = offsetof(struct file_struct, flags) + sizeof f.flags;
90         checksum_len = protocol_version < 21 ? 2 : MD4_SUM_LENGTH;
91 }
92
93 static int show_filelist_p(void)
94 {
95         return verbose && xfer_dirs && !am_server;
96 }
97
98 static void start_filelist_progress(char *kind)
99 {
100         rprintf(FINFO, "%s ... ", kind);
101         if (verbose > 1 || do_progress)
102                 rprintf(FINFO, "\n");
103         rflush(FINFO);
104 }
105
106 static void emit_filelist_progress(int count)
107 {
108         rprintf(FINFO, " %d files...\r", count);
109 }
110
111 static void maybe_emit_filelist_progress(int count)
112 {
113         if (do_progress && show_filelist_p() && (count % 100) == 0)
114                 emit_filelist_progress(count);
115 }
116
117 static void finish_filelist_progress(const struct file_list *flist)
118 {
119         if (do_progress) {
120                 /* This overwrites the progress line */
121                 rprintf(FINFO, "%d file%sto consider\n",
122                         flist->count, flist->count == 1 ? " " : "s ");
123         } else
124                 rprintf(FINFO, "done\n");
125 }
126
127 void show_flist_stats(void)
128 {
129         /* Nothing yet */
130 }
131
132 static void list_file_entry(struct file_struct *f)
133 {
134         char perms[11];
135
136         if (!f->basename) {
137                 /* this can happen if duplicate names were removed */
138                 return;
139         }
140
141         permstring(perms, f->mode);
142
143 #ifdef SUPPORT_LINKS
144         if (preserve_links && S_ISLNK(f->mode)) {
145                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
146                         perms,
147                         (double)f->length, timestring(f->modtime),
148                         f_name(f, NULL), f->u.link);
149         } else
150 #endif
151         {
152                 rprintf(FINFO, "%s %11.0f %s %s\n",
153                         perms,
154                         (double)f->length, timestring(f->modtime),
155                         f_name(f, NULL));
156         }
157 }
158
159 /**
160  * Stat either a symlink or its referent, depending on the settings of
161  * copy_links, copy_unsafe_links, etc.
162  *
163  * @retval -1 on error
164  *
165  * @retval 0 for success
166  *
167  * @post If @p path is a symlink, then @p linkbuf (of size @c
168  * MAXPATHLEN) contains the symlink target.
169  *
170  * @post @p buffer contains information about the link or the
171  * referrent as appropriate, if they exist.
172  **/
173 static int readlink_stat(const char *path, STRUCT_STAT *buffer, char *linkbuf)
174 {
175 #ifdef SUPPORT_LINKS
176         if (copy_links)
177                 return do_stat(path, buffer);
178         if (link_stat(path, buffer, 0) < 0)
179                 return -1;
180         if (S_ISLNK(buffer->st_mode)) {
181                 int l = readlink((char *)path, linkbuf, MAXPATHLEN - 1);
182                 if (l == -1)
183                         return -1;
184                 linkbuf[l] = 0;
185                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
186                         if (verbose > 1) {
187                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
188                                         path, linkbuf);
189                         }
190                         return do_stat(path, buffer);
191                 }
192         }
193         return 0;
194 #else
195         return do_stat(path, buffer);
196 #endif
197 }
198
199 int link_stat(const char *path, STRUCT_STAT *buffer, int follow_dirlinks)
200 {
201 #ifdef SUPPORT_LINKS
202         if (copy_links)
203                 return do_stat(path, buffer);
204         if (do_lstat(path, buffer) < 0)
205                 return -1;
206         if (follow_dirlinks && S_ISLNK(buffer->st_mode)) {
207                 STRUCT_STAT st;
208                 if (do_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
209                         *buffer = st;
210         }
211         return 0;
212 #else
213         return do_stat(path, buffer);
214 #endif
215 }
216
217 /* This function is used to check if a file should be included/excluded
218  * from the list of files based on its name and type etc.  The value of
219  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
220 static int is_excluded(char *fname, int is_dir, int filter_level)
221 {
222 #if 0 /* This currently never happens, so avoid a useless compare. */
223         if (filter_level == NO_FILTERS)
224                 return 0;
225 #endif
226         if (fname) {
227                 /* never exclude '.', even if somebody does --exclude '*' */
228                 if (fname[0] == '.' && !fname[1])
229                         return 0;
230                 /* Handle the -R version of the '.' dir. */
231                 if (fname[0] == '/') {
232                         int len = strlen(fname);
233                         if (fname[len-1] == '.' && fname[len-2] == '/')
234                                 return 0;
235                 }
236         }
237         if (server_filter_list.head
238             && check_filter(&server_filter_list, fname, is_dir) < 0)
239                 return 1;
240         if (filter_level != ALL_FILTERS)
241                 return 0;
242         if (filter_list.head
243             && check_filter(&filter_list, fname, is_dir) < 0)
244                 return 1;
245         return 0;
246 }
247
248 static int to_wire_mode(mode_t mode)
249 {
250 #ifdef SUPPORT_LINKS
251         if (S_ISLNK(mode) && (_S_IFLNK != 0120000))
252                 return (mode & ~(_S_IFMT)) | 0120000;
253 #endif
254         return (int)mode;
255 }
256
257 static mode_t from_wire_mode(int mode)
258 {
259         if ((mode & (_S_IFMT)) == 0120000 && (_S_IFLNK != 0120000))
260                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
261         return (mode_t)mode;
262 }
263
264 static void send_directory(int f, struct file_list *flist,
265                            char *fbuf, int len);
266
267 static char *flist_dir;
268 static int flist_dir_len;
269
270
271 /**
272  * Make sure @p flist is big enough to hold at least @p flist->count
273  * entries.
274  **/
275 void flist_expand(struct file_list *flist)
276 {
277         struct file_struct **new_ptr;
278
279         if (flist->count < flist->malloced)
280                 return;
281
282         if (flist->malloced < FLIST_START)
283                 flist->malloced = FLIST_START;
284         else if (flist->malloced >= FLIST_LINEAR)
285                 flist->malloced += FLIST_LINEAR;
286         else
287                 flist->malloced *= 2;
288
289         /*
290          * In case count jumped or we are starting the list
291          * with a known size just set it.
292          */
293         if (flist->malloced < flist->count)
294                 flist->malloced = flist->count;
295
296         new_ptr = realloc_array(flist->files, struct file_struct *,
297                                 flist->malloced);
298
299         if (verbose >= 2 && flist->malloced != FLIST_START) {
300                 rprintf(FINFO, "[%s] expand file_list to %.0f bytes, did%s move\n",
301                     who_am_i(),
302                     (double)sizeof flist->files[0] * flist->malloced,
303                     (new_ptr == flist->files) ? " not" : "");
304         }
305
306         flist->files = new_ptr;
307
308         if (!flist->files)
309                 out_of_memory("flist_expand");
310 }
311
312 static void send_file_entry(struct file_struct *file, int f)
313 {
314         unsigned short flags;
315         static time_t modtime;
316         static mode_t mode;
317         static int64 dev;
318         static dev_t rdev;
319         static uint32 rdev_major;
320         static uid_t uid;
321         static gid_t gid;
322         static char lastname[MAXPATHLEN];
323         char fname[MAXPATHLEN];
324         int l1, l2;
325
326         if (f < 0)
327                 return;
328
329         if (!file) {
330                 write_byte(f, 0);
331                 modtime = 0, mode = 0;
332                 dev = 0, rdev = makedev(0, 0);
333                 rdev_major = 0;
334                 uid = 0, gid = 0;
335                 *lastname = '\0';
336                 return;
337         }
338
339         io_write_phase = "send_file_entry";
340
341         f_name(file, fname);
342
343         flags = file->flags & XMIT_TOP_DIR;
344
345         if (file->mode == mode)
346                 flags |= XMIT_SAME_MODE;
347         else
348                 mode = file->mode;
349         if ((preserve_devices && IS_DEVICE(mode))
350          || (preserve_specials && IS_SPECIAL(mode))) {
351                 if (protocol_version < 28) {
352                         if (file->u.rdev == rdev)
353                                 flags |= XMIT_SAME_RDEV_pre28;
354                         else
355                                 rdev = file->u.rdev;
356                 } else {
357                         rdev = file->u.rdev;
358                         if ((uint32)major(rdev) == rdev_major)
359                                 flags |= XMIT_SAME_RDEV_MAJOR;
360                         else
361                                 rdev_major = major(rdev);
362                         if ((uint32)minor(rdev) <= 0xFFu)
363                                 flags |= XMIT_RDEV_MINOR_IS_SMALL;
364                 }
365         } else if (protocol_version < 28)
366                 rdev = makedev(0, 0);
367         if (file->uid == uid)
368                 flags |= XMIT_SAME_UID;
369         else
370                 uid = file->uid;
371         if (file->gid == gid)
372                 flags |= XMIT_SAME_GID;
373         else
374                 gid = file->gid;
375         if (file->modtime == modtime)
376                 flags |= XMIT_SAME_TIME;
377         else
378                 modtime = file->modtime;
379
380 #ifdef SUPPORT_HARD_LINKS
381         if (file->link_u.idev) {
382                 if (file->F_DEV == dev) {
383                         if (protocol_version >= 28)
384                                 flags |= XMIT_SAME_DEV;
385                 } else
386                         dev = file->F_DEV;
387                 flags |= XMIT_HAS_IDEV_DATA;
388         }
389 #endif
390
391         for (l1 = 0;
392             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
393             l1++) {}
394         l2 = strlen(fname+l1);
395
396         if (l1 > 0)
397                 flags |= XMIT_SAME_NAME;
398         if (l2 > 255)
399                 flags |= XMIT_LONG_NAME;
400
401         /* We must make sure we don't send a zero flag byte or the
402          * other end will terminate the flist transfer.  Note that
403          * the use of XMIT_TOP_DIR on a non-dir has no meaning, so
404          * it's harmless way to add a bit to the first flag byte. */
405         if (protocol_version >= 28) {
406                 if (!flags && !S_ISDIR(mode))
407                         flags |= XMIT_TOP_DIR;
408                 if ((flags & 0xFF00) || !flags) {
409                         flags |= XMIT_EXTENDED_FLAGS;
410                         write_byte(f, flags);
411                         write_byte(f, flags >> 8);
412                 } else
413                         write_byte(f, flags);
414         } else {
415                 if (!(flags & 0xFF))
416                         flags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
417                 write_byte(f, flags);
418         }
419         if (flags & XMIT_SAME_NAME)
420                 write_byte(f, l1);
421         if (flags & XMIT_LONG_NAME)
422                 write_int(f, l2);
423         else
424                 write_byte(f, l2);
425         write_buf(f, fname + l1, l2);
426
427         write_longint(f, file->length);
428         if (!(flags & XMIT_SAME_TIME))
429                 write_int(f, modtime);
430         if (!(flags & XMIT_SAME_MODE))
431                 write_int(f, to_wire_mode(mode));
432         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
433                 if (!numeric_ids)
434                         add_uid(uid);
435                 write_int(f, uid);
436         }
437         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
438                 if (!numeric_ids)
439                         add_gid(gid);
440                 write_int(f, gid);
441         }
442         if ((preserve_devices && IS_DEVICE(mode))
443          || (preserve_specials && IS_SPECIAL(mode))) {
444                 if (protocol_version < 28) {
445                         if (!(flags & XMIT_SAME_RDEV_pre28))
446                                 write_int(f, (int)rdev);
447                 } else {
448                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
449                                 write_int(f, major(rdev));
450                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
451                                 write_byte(f, minor(rdev));
452                         else
453                                 write_int(f, minor(rdev));
454                 }
455         }
456
457 #ifdef SUPPORT_LINKS
458         if (preserve_links && S_ISLNK(mode)) {
459                 int len = strlen(file->u.link);
460                 write_int(f, len);
461                 write_buf(f, file->u.link, len);
462         }
463 #endif
464
465 #ifdef SUPPORT_HARD_LINKS
466         if (flags & XMIT_HAS_IDEV_DATA) {
467                 if (protocol_version < 26) {
468                         /* 32-bit dev_t and ino_t */
469                         write_int(f, dev);
470                         write_int(f, file->F_INODE);
471                 } else {
472                         /* 64-bit dev_t and ino_t */
473                         if (!(flags & XMIT_SAME_DEV))
474                                 write_longint(f, dev);
475                         write_longint(f, file->F_INODE);
476                 }
477         }
478 #endif
479
480         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
481                 char *sum;
482                 if (S_ISREG(mode))
483                         sum = file->u.sum;
484                 else {
485                         /* Prior to 28, we sent a useless set of nulls. */
486                         sum = empty_sum;
487                 }
488                 write_buf(f, sum, checksum_len);
489         }
490
491         strlcpy(lastname, fname, MAXPATHLEN);
492
493         io_write_phase = "unknown";
494 }
495
496 static struct file_struct *receive_file_entry(struct file_list *flist,
497                                               unsigned short flags, int f)
498 {
499         static time_t modtime;
500         static mode_t mode;
501         static int64 dev;
502         static dev_t rdev;
503         static uint32 rdev_major;
504         static uid_t uid;
505         static gid_t gid;
506         static char lastname[MAXPATHLEN], *lastdir;
507         static int lastdir_depth, lastdir_len = -1;
508         static unsigned int del_hier_name_len = 0;
509         static int in_del_hier = 0;
510         char thisname[MAXPATHLEN];
511         unsigned int l1 = 0, l2 = 0;
512         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
513         OFF_T file_length;
514         char *basename, *dirname, *bp;
515         struct file_struct *file;
516
517         if (!flist) {
518                 modtime = 0, mode = 0;
519                 dev = 0, rdev = makedev(0, 0);
520                 rdev_major = 0;
521                 uid = 0, gid = 0;
522                 *lastname = '\0';
523                 lastdir_len = -1;
524                 in_del_hier = 0;
525                 return NULL;
526         }
527
528         if (flags & XMIT_SAME_NAME)
529                 l1 = read_byte(f);
530
531         if (flags & XMIT_LONG_NAME)
532                 l2 = read_int(f);
533         else
534                 l2 = read_byte(f);
535
536         if (l2 >= MAXPATHLEN - l1) {
537                 rprintf(FERROR,
538                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s\n",
539                         flags, l1, l2, lastname);
540                 overflow_exit("receive_file_entry");
541         }
542
543         strlcpy(thisname, lastname, l1 + 1);
544         read_sbuf(f, &thisname[l1], l2);
545         thisname[l1 + l2] = 0;
546
547         strlcpy(lastname, thisname, MAXPATHLEN);
548
549         clean_fname(thisname, 0);
550
551         if (sanitize_paths)
552                 sanitize_path(thisname, thisname, "", 0);
553
554         if ((basename = strrchr(thisname, '/')) != NULL) {
555                 dirname_len = ++basename - thisname; /* counts future '\0' */
556                 if (lastdir_len == dirname_len - 1
557                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
558                         dirname = lastdir;
559                         dirname_len = 0; /* indicates no copy is needed */
560                 } else
561                         dirname = thisname;
562         } else {
563                 basename = thisname;
564                 dirname = NULL;
565                 dirname_len = 0;
566         }
567         basename_len = strlen(basename) + 1; /* count the '\0' */
568
569         file_length = read_longint(f);
570         if (!(flags & XMIT_SAME_TIME))
571                 modtime = (time_t)read_int(f);
572         if (!(flags & XMIT_SAME_MODE))
573                 mode = from_wire_mode(read_int(f));
574
575         if (chmod_modes && !S_ISLNK(mode))
576                 mode = tweak_mode(mode, chmod_modes);
577
578         if (preserve_uid && !(flags & XMIT_SAME_UID))
579                 uid = (uid_t)read_int(f);
580         if (preserve_gid && !(flags & XMIT_SAME_GID))
581                 gid = (gid_t)read_int(f);
582
583         if ((preserve_devices && IS_DEVICE(mode))
584          || (preserve_specials && IS_SPECIAL(mode))) {
585                 if (protocol_version < 28) {
586                         if (!(flags & XMIT_SAME_RDEV_pre28))
587                                 rdev = (dev_t)read_int(f);
588                 } else {
589                         uint32 rdev_minor;
590                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
591                                 rdev_major = read_int(f);
592                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
593                                 rdev_minor = read_byte(f);
594                         else
595                                 rdev_minor = read_int(f);
596                         rdev = makedev(rdev_major, rdev_minor);
597                 }
598         } else if (protocol_version < 28)
599                 rdev = makedev(0, 0);
600
601 #ifdef SUPPORT_LINKS
602         if (preserve_links && S_ISLNK(mode)) {
603                 linkname_len = read_int(f) + 1; /* count the '\0' */
604                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
605                         rprintf(FERROR, "overflow: linkname_len=%d\n",
606                                 linkname_len - 1);
607                         overflow_exit("receive_file_entry");
608                 }
609         }
610         else
611 #endif
612                 linkname_len = 0;
613
614         sum_len = always_checksum && S_ISREG(mode) ? MD4_SUM_LENGTH : 0;
615
616         alloc_len = file_struct_len + dirname_len + basename_len
617                   + linkname_len + sum_len;
618         bp = pool_alloc(flist->file_pool, alloc_len, "receive_file_entry");
619
620         file = (struct file_struct *)bp;
621         memset(bp, 0, file_struct_len);
622         bp += file_struct_len;
623
624         file->modtime = modtime;
625         file->length = file_length;
626         file->mode = mode;
627         file->uid = uid;
628         file->gid = gid;
629
630         if (dirname_len) {
631                 file->dirname = lastdir = bp;
632                 lastdir_len = dirname_len - 1;
633                 memcpy(bp, dirname, dirname_len - 1);
634                 bp += dirname_len;
635                 bp[-1] = '\0';
636                 lastdir_depth = count_dir_elements(lastdir);
637                 file->dir.depth = lastdir_depth + 1;
638                 if (lastdir_depth >= max_dir_depth)
639                         max_dir_depth = lastdir_depth + 1;
640         } else if (dirname) {
641                 file->dirname = dirname; /* we're reusing lastname */
642                 file->dir.depth = lastdir_depth + 1;
643         } else
644                 file->dir.depth = 1;
645
646         if (S_ISDIR(mode)) {
647                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
648                         file->dir.depth--;
649                 if (flags & XMIT_TOP_DIR) {
650                         in_del_hier = recurse;
651                         del_hier_name_len = file->dir.depth == 0 ? 0 : l1 + l2;
652                         if (relative_paths && del_hier_name_len > 2
653                             && lastname[del_hier_name_len-1] == '.'
654                             && lastname[del_hier_name_len-2] == '/')
655                                 del_hier_name_len -= 2;
656                         file->flags |= FLAG_TOP_DIR | FLAG_DEL_HERE;
657                 } else if (in_del_hier) {
658                         if (!relative_paths || !del_hier_name_len
659                          || (l1 >= del_hier_name_len
660                           && lastname[del_hier_name_len] == '/'))
661                                 file->flags |= FLAG_DEL_HERE;
662                         else
663                                 in_del_hier = 0;
664                 }
665         }
666
667         file->basename = bp;
668         memcpy(bp, basename, basename_len);
669         bp += basename_len;
670
671         if ((preserve_devices && IS_DEVICE(mode))
672          || (preserve_specials && IS_SPECIAL(mode)))
673                 file->u.rdev = rdev;
674
675 #ifdef SUPPORT_LINKS
676         if (linkname_len) {
677                 file->u.link = bp;
678                 read_sbuf(f, bp, linkname_len - 1);
679                 if (sanitize_paths)
680                         sanitize_path(bp, bp, "", lastdir_depth);
681                 bp += linkname_len;
682         }
683 #endif
684
685 #ifdef SUPPORT_HARD_LINKS
686         if (preserve_hard_links && protocol_version < 28 && S_ISREG(mode))
687                 flags |= XMIT_HAS_IDEV_DATA;
688         if (flags & XMIT_HAS_IDEV_DATA) {
689                 int64 inode;
690                 if (protocol_version < 26) {
691                         dev = read_int(f);
692                         inode = read_int(f);
693                 } else {
694                         if (!(flags & XMIT_SAME_DEV))
695                                 dev = read_longint(f);
696                         inode = read_longint(f);
697                 }
698                 if (flist->hlink_pool) {
699                         file->link_u.idev = pool_talloc(flist->hlink_pool,
700                             struct idev, 1, "inode_table");
701                         file->F_INODE = inode;
702                         file->F_DEV = dev;
703                 }
704         }
705 #endif
706
707         if (always_checksum && (sum_len || protocol_version < 28)) {
708                 char *sum;
709                 if (sum_len) {
710                         file->u.sum = sum = bp;
711                         /*bp += sum_len;*/
712                 } else {
713                         /* Prior to 28, we get a useless set of nulls. */
714                         sum = empty_sum;
715                 }
716                 read_buf(f, sum, checksum_len);
717         }
718
719         if (!preserve_perms) {
720                 /* set an appropriate set of permissions based on original
721                  * permissions and umask. This emulates what GNU cp does */
722                 file->mode &= ~orig_umask;
723         }
724
725         return file;
726 }
727
728 /**
729  * Create a file_struct for a named file by reading its stat()
730  * information and performing extensive checks against global
731  * options.
732  *
733  * @return the new file, or NULL if there was an error or this file
734  * should be excluded.
735  *
736  * @todo There is a small optimization opportunity here to avoid
737  * stat()ing the file in some circumstances, which has a certain cost.
738  * We are called immediately after doing readdir(), and so we may
739  * already know the d_type of the file.  We could for example avoid
740  * statting directories if we're not recursing, but this is not a very
741  * important case.  Some systems may not have d_type.
742  **/
743 struct file_struct *make_file(char *fname, struct file_list *flist,
744                               STRUCT_STAT *stp, unsigned short flags,
745                               int filter_level)
746 {
747         static char *lastdir;
748         static int lastdir_len = -1;
749         struct file_struct *file;
750         STRUCT_STAT st;
751         char sum[SUM_LENGTH];
752         char thisname[MAXPATHLEN];
753         char linkname[MAXPATHLEN];
754         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
755         char *basename, *dirname, *bp;
756
757         if (!flist || !flist->count)    /* Ignore lastdir when invalid. */
758                 lastdir_len = -1;
759
760         if (strlcpy(thisname, fname, sizeof thisname)
761             >= sizeof thisname - flist_dir_len) {
762                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
763                 return NULL;
764         }
765         clean_fname(thisname, 0);
766         if (sanitize_paths)
767                 sanitize_path(thisname, thisname, "", 0);
768
769         memset(sum, 0, SUM_LENGTH);
770
771         if (stp && S_ISDIR(stp->st_mode))
772                 st = *stp; /* Needed for "symlink/." with --relative. */
773         else if (readlink_stat(thisname, &st, linkname) != 0) {
774                 int save_errno = errno;
775                 /* See if file is excluded before reporting an error. */
776                 if (filter_level != NO_FILTERS
777                     && is_excluded(thisname, 0, filter_level))
778                         return NULL;
779                 if (save_errno == ENOENT) {
780 #ifdef SUPPORT_LINKS
781                         /* Avoid "vanished" error if symlink points nowhere. */
782                         if (copy_links && do_lstat(thisname, &st) == 0
783                             && S_ISLNK(st.st_mode)) {
784                                 io_error |= IOERR_GENERAL;
785                                 rprintf(FERROR, "symlink has no referent: %s\n",
786                                         full_fname(thisname));
787                         } else
788 #endif
789                         {
790                                 enum logcode c = am_daemon && protocol_version < 28
791                                     ? FERROR : FINFO;
792                                 io_error |= IOERR_VANISHED;
793                                 rprintf(c, "file has vanished: %s\n",
794                                         full_fname(thisname));
795                         }
796                 } else {
797                         io_error |= IOERR_GENERAL;
798                         rsyserr(FERROR, save_errno, "readlink %s failed",
799                                 full_fname(thisname));
800                 }
801                 return NULL;
802         }
803
804         /* backup.c calls us with filter_level set to NO_FILTERS. */
805         if (filter_level == NO_FILTERS)
806                 goto skip_filters;
807
808         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
809                 rprintf(FINFO, "skipping directory %s\n", thisname);
810                 return NULL;
811         }
812
813         /* We only care about directories because we need to avoid recursing
814          * into a mount-point directory, not to avoid copying a symlinked
815          * file if -L (or similar) was specified. */
816         if (one_file_system && st.st_dev != filesystem_dev
817          && S_ISDIR(st.st_mode)) {
818                 if (one_file_system > 1) {
819                         if (verbose > 2) {
820                                 rprintf(FINFO, "skipping mount-point dir %s\n",
821                                         thisname);
822                         }
823                         return NULL;
824                 }
825                 flags |= FLAG_MOUNT_POINT;
826         }
827
828         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level))
829                 return NULL;
830
831         if (lp_ignore_nonreadable(module_id)) {
832 #ifdef SUPPORT_LINKS
833                 if (!S_ISLNK(st.st_mode))
834 #endif
835                         if (access(thisname, R_OK) != 0)
836                                 return NULL;
837         }
838
839   skip_filters:
840
841         if (verbose > 2) {
842                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
843                         who_am_i(), thisname, filter_level);
844         }
845
846         if ((basename = strrchr(thisname, '/')) != NULL) {
847                 dirname_len = ++basename - thisname; /* counts future '\0' */
848                 if (lastdir_len == dirname_len - 1
849                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
850                         dirname = lastdir;
851                         dirname_len = 0; /* indicates no copy is needed */
852                 } else
853                         dirname = thisname;
854         } else {
855                 basename = thisname;
856                 dirname = NULL;
857                 dirname_len = 0;
858         }
859         basename_len = strlen(basename) + 1; /* count the '\0' */
860
861 #ifdef SUPPORT_LINKS
862         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
863 #else
864         linkname_len = 0;
865 #endif
866
867         sum_len = always_checksum && am_sender && S_ISREG(st.st_mode)
868                 ? MD4_SUM_LENGTH : 0;
869
870         alloc_len = file_struct_len + dirname_len + basename_len
871             + linkname_len + sum_len;
872         if (flist)
873                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
874         else {
875                 if (!(bp = new_array(char, alloc_len)))
876                         out_of_memory("make_file");
877         }
878
879         file = (struct file_struct *)bp;
880         memset(bp, 0, file_struct_len);
881         bp += file_struct_len;
882
883         file->flags = flags;
884         file->modtime = st.st_mtime;
885         file->length = st.st_size;
886         file->mode = st.st_mode;
887         file->uid = st.st_uid;
888         file->gid = st.st_gid;
889
890 #ifdef SUPPORT_HARD_LINKS
891         if (flist && flist->hlink_pool) {
892                 if (protocol_version < 28) {
893                         if (S_ISREG(st.st_mode))
894                                 file->link_u.idev = pool_talloc(
895                                     flist->hlink_pool, struct idev, 1,
896                                     "inode_table");
897                 } else {
898                         if (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
899                                 file->link_u.idev = pool_talloc(
900                                     flist->hlink_pool, struct idev, 1,
901                                     "inode_table");
902                 }
903         }
904         if (file->link_u.idev) {
905                 file->F_DEV = st.st_dev;
906                 file->F_INODE = st.st_ino;
907         }
908 #endif
909
910         if (dirname_len) {
911                 file->dirname = lastdir = bp;
912                 lastdir_len = dirname_len - 1;
913                 memcpy(bp, dirname, dirname_len - 1);
914                 bp += dirname_len;
915                 bp[-1] = '\0';
916         } else if (dirname)
917                 file->dirname = dirname;
918
919         file->basename = bp;
920         memcpy(bp, basename, basename_len);
921         bp += basename_len;
922
923 #ifdef HAVE_STRUCT_STAT_ST_RDEV
924         if ((preserve_devices && IS_DEVICE(st.st_mode))
925          || (preserve_specials && IS_SPECIAL(st.st_mode)))
926                 file->u.rdev = st.st_rdev;
927 #endif
928
929 #ifdef SUPPORT_LINKS
930         if (linkname_len) {
931                 file->u.link = bp;
932                 memcpy(bp, linkname, linkname_len);
933                 bp += linkname_len;
934         }
935 #endif
936
937         if (sum_len) {
938                 file->u.sum = bp;
939                 file_checksum(thisname, bp, st.st_size);
940                 /*bp += sum_len;*/
941         }
942
943         file->dir.root = flist_dir;
944
945         /* This code is only used by the receiver when it is building
946          * a list of files for a delete pass. */
947         if (keep_dirlinks && linkname_len && flist) {
948                 STRUCT_STAT st2;
949                 int save_mode = file->mode;
950                 file->mode = S_IFDIR; /* Find a directory with our name. */
951                 if (flist_find(the_file_list, file) >= 0
952                     && do_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
953                         file->modtime = st2.st_mtime;
954                         file->length = st2.st_size;
955                         file->mode = st2.st_mode;
956                         file->uid = st2.st_uid;
957                         file->gid = st2.st_gid;
958                         file->u.link = NULL;
959                 } else
960                         file->mode = save_mode;
961         }
962
963         if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
964                 stats.total_size += st.st_size;
965
966         return file;
967 }
968
969 static struct file_struct *send_file_name(int f, struct file_list *flist,
970                                           char *fname, STRUCT_STAT *stp,
971                                           unsigned short flags)
972 {
973         struct file_struct *file;
974
975         file = make_file(fname, flist, stp, flags,
976                          f == -2 ? SERVER_FILTERS : ALL_FILTERS);
977         if (!file)
978                 return NULL;
979
980         if (chmod_modes && !S_ISLNK(file->mode))
981                 file->mode = tweak_mode(file->mode, chmod_modes);
982
983         maybe_emit_filelist_progress(flist->count + flist_count_offset);
984
985         flist_expand(flist);
986
987         if (file->basename[0]) {
988                 flist->files[flist->count++] = file;
989                 send_file_entry(file, f);
990         }
991         return file;
992 }
993
994 static void send_if_directory(int f, struct file_list *flist,
995                               struct file_struct *file,
996                               char *fbuf, unsigned int ol)
997 {
998         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
999
1000         if (S_ISDIR(file->mode)
1001             && !(file->flags & FLAG_MOUNT_POINT) && f_name(file, fbuf)) {
1002                 void *save_filters;
1003                 unsigned int len = strlen(fbuf);
1004                 if (len > 1 && fbuf[len-1] == '/')
1005                         fbuf[--len] = '\0';
1006                 if (len >= MAXPATHLEN - 1) {
1007                         io_error |= IOERR_GENERAL;
1008                         rprintf(FERROR, "skipping long-named directory: %s\n",
1009                                 full_fname(fbuf));
1010                         return;
1011                 }
1012                 save_filters = push_local_filters(fbuf, len);
1013                 send_directory(f, flist, fbuf, len);
1014                 pop_local_filters(save_filters);
1015                 fbuf[ol] = '\0';
1016                 if (is_dot_dir)
1017                         fbuf[ol-1] = '.';
1018         }
1019 }
1020
1021 /* This function is normally called by the sender, but the receiving side also
1022  * calls it from get_dirlist() with f set to -1 so that we just construct the
1023  * file list in memory without sending it over the wire.  Also, get_dirlist()
1024  * might call this with f set to -2, which also indicates that local filter
1025  * rules should be ignored. */
1026 static void send_directory(int f, struct file_list *flist,
1027                            char *fbuf, int len)
1028 {
1029         struct dirent *di;
1030         unsigned remainder;
1031         char *p;
1032         DIR *d;
1033         int start = flist->count;
1034
1035         if (!(d = opendir(fbuf))) {
1036                 io_error |= IOERR_GENERAL;
1037                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1038                 return;
1039         }
1040
1041         p = fbuf + len;
1042         if (len != 1 || *fbuf != '/')
1043                 *p++ = '/';
1044         *p = '\0';
1045         remainder = MAXPATHLEN - (p - fbuf);
1046
1047         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1048                 char *dname = d_name(di);
1049                 if (dname[0] == '.' && (dname[1] == '\0'
1050                     || (dname[1] == '.' && dname[2] == '\0')))
1051                         continue;
1052                 if (strlcpy(p, dname, remainder) >= remainder) {
1053                         io_error |= IOERR_GENERAL;
1054                         rprintf(FINFO,
1055                                 "cannot send long-named file %s\n",
1056                                 full_fname(fbuf));
1057                         continue;
1058                 }
1059
1060                 send_file_name(f, flist, fbuf, NULL, 0);
1061         }
1062
1063         fbuf[len] = '\0';
1064
1065         if (errno) {
1066                 io_error |= IOERR_GENERAL;
1067                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1068         }
1069
1070         closedir(d);
1071
1072         if (recurse) {
1073                 int i, end = flist->count - 1;
1074                 for (i = start; i <= end; i++)
1075                         send_if_directory(f, flist, flist->files[i], fbuf, len);
1076         }
1077 }
1078
1079 struct file_list *send_file_list(int f, int argc, char *argv[])
1080 {
1081         int len;
1082         STRUCT_STAT st;
1083         char *p, *dir, olddir[sizeof curr_dir];
1084         char lastpath[MAXPATHLEN] = "";
1085         struct file_list *flist;
1086         struct timeval start_tv, end_tv;
1087         int64 start_write;
1088         int use_ff_fd = 0;
1089
1090         if (show_filelist_p())
1091                 start_filelist_progress("building file list");
1092
1093         start_write = stats.total_written;
1094         gettimeofday(&start_tv, NULL);
1095
1096         flist = flist_new(WITH_HLINK, "send_file_list");
1097
1098         io_start_buffering_out();
1099         if (filesfrom_fd >= 0) {
1100                 if (argv[0] && !push_dir(argv[0])) {
1101                         rsyserr(FERROR, errno, "push_dir %s failed",
1102                                 full_fname(argv[0]));
1103                         exit_cleanup(RERR_FILESELECT);
1104                 }
1105                 use_ff_fd = 1;
1106         }
1107
1108         while (1) {
1109                 char fbuf[MAXPATHLEN];
1110                 char *fn;
1111                 int is_dot_dir;
1112
1113                 if (use_ff_fd) {
1114                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1115                                 break;
1116                         sanitize_path(fbuf, fbuf, "", 0);
1117                 } else {
1118                         if (argc-- == 0)
1119                                 break;
1120                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1121                         if (sanitize_paths)
1122                                 sanitize_path(fbuf, fbuf, "", 0);
1123                 }
1124
1125                 len = strlen(fbuf);
1126                 if (relative_paths) {
1127                         /* We clean up fbuf below. */
1128                         is_dot_dir = 0;
1129                 } else if (!len || fbuf[len - 1] == '/') {
1130                         if (len == 2 && fbuf[0] == '.') {
1131                                 /* Turn "./" into just "." rather than "./." */
1132                                 fbuf[1] = '\0';
1133                         } else {
1134                                 if (len + 1 >= MAXPATHLEN)
1135                                         overflow_exit("send_file_list");
1136                                 fbuf[len++] = '.';
1137                                 fbuf[len] = '\0';
1138                         }
1139                         is_dot_dir = 1;
1140                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1141                     && (len == 2 || fbuf[len-3] == '/')) {
1142                         if (len + 2 >= MAXPATHLEN)
1143                                 overflow_exit("send_file_list");
1144                         fbuf[len++] = '/';
1145                         fbuf[len++] = '.';
1146                         fbuf[len] = '\0';
1147                         is_dot_dir = 1;
1148                 } else {
1149                         is_dot_dir = fbuf[len-1] == '.'
1150                                    && (len == 1 || fbuf[len-2] == '/');
1151                 }
1152
1153                 if (link_stat(fbuf, &st, keep_dirlinks) != 0) {
1154                         io_error |= IOERR_GENERAL;
1155                         rsyserr(FERROR, errno, "link_stat %s failed",
1156                                 full_fname(fbuf));
1157                         continue;
1158                 }
1159
1160                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1161                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1162                         continue;
1163                 }
1164
1165                 dir = NULL;
1166                 olddir[0] = '\0';
1167
1168                 if (!relative_paths) {
1169                         p = strrchr(fbuf, '/');
1170                         if (p) {
1171                                 *p = '\0';
1172                                 if (p == fbuf)
1173                                         dir = "/";
1174                                 else
1175                                         dir = fbuf;
1176                                 len -= p - fbuf + 1;
1177                                 fn = p + 1;
1178                         } else
1179                                 fn = fbuf;
1180                 } else {
1181                         if ((p = strstr(fbuf, "/./")) != NULL) {
1182                                 *p = '\0';
1183                                 if (p == fbuf)
1184                                         dir = "/";
1185                                 else
1186                                         dir = fbuf;
1187                                 len -= p - fbuf + 3;
1188                                 fn = p + 3;
1189                         } else
1190                                 fn = fbuf;
1191                         /* Get rid of trailing "/" and "/.". */
1192                         while (len) {
1193                                 if (fn[len - 1] == '/') {
1194                                         is_dot_dir = 1;
1195                                         if (!--len && !dir) {
1196                                                 len++;
1197                                                 break;
1198                                         }
1199                                 }
1200                                 else if (len >= 2 && fn[len - 1] == '.'
1201                                                   && fn[len - 2] == '/') {
1202                                         is_dot_dir = 1;
1203                                         if (!(len -= 2) && !dir) {
1204                                                 len++;
1205                                                 break;
1206                                         }
1207                                 } else
1208                                         break;
1209                         }
1210                         fn[len] = '\0';
1211                         /* Reject a ".." dir in the active part of the path. */
1212                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1213                                 if ((p[2] == '/' || p[2] == '\0')
1214                                  && (p == fn || p[-1] == '/')) {
1215                                         rprintf(FERROR,
1216                                             "found \"..\" dir in relative path: %s\n",
1217                                             fbuf);
1218                                         exit_cleanup(RERR_SYNTAX);
1219                                 }
1220                         }
1221                 }
1222
1223                 if (!*fn) {
1224                         len = 1;
1225                         fn = ".";
1226                 }
1227
1228                 if (dir && *dir) {
1229                         static char *lastdir;
1230                         static int lastdir_len;
1231
1232                         strlcpy(olddir, curr_dir, sizeof olddir);
1233
1234                         if (!push_dir(dir)) {
1235                                 io_error |= IOERR_GENERAL;
1236                                 rsyserr(FERROR, errno, "push_dir %s failed",
1237                                         full_fname(dir));
1238                                 continue;
1239                         }
1240
1241                         if (lastdir && strcmp(lastdir, dir) == 0) {
1242                                 flist_dir = lastdir;
1243                                 flist_dir_len = lastdir_len;
1244                         } else {
1245                                 flist_dir = lastdir = strdup(dir);
1246                                 flist_dir_len = lastdir_len = strlen(dir);
1247                         }
1248                 }
1249
1250                 if (fn != fbuf)
1251                         memmove(fbuf, fn, len + 1);
1252
1253                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1254                         /* Send the implied directories at the start of the
1255                          * source spec, so we get their permissions right. */
1256                         char *lp = lastpath, *slash = fbuf;
1257                         *p = '\0';
1258                         /* Skip any initial directories in our path that we
1259                          * have in common with lastpath. */
1260                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1261                                 if (*fn == '/')
1262                                         slash = fn;
1263                         }
1264                         *p = '/';
1265                         if (fn != p || (*lp && *lp != '/')) {
1266                                 int save_copy_links = copy_links;
1267                                 int save_xfer_dirs = xfer_dirs;
1268                                 copy_links = copy_unsafe_links;
1269                                 xfer_dirs = 1;
1270                                 while ((slash = strchr(slash+1, '/')) != 0) {
1271                                         *slash = '\0';
1272                                         send_file_name(f, flist, fbuf, NULL, 0);
1273                                         *slash = '/';
1274                                 }
1275                                 copy_links = save_copy_links;
1276                                 xfer_dirs = save_xfer_dirs;
1277                                 *p = '\0';
1278                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1279                                 *p = '/';
1280                         }
1281                 }
1282
1283                 if (one_file_system)
1284                         filesystem_dev = st.st_dev;
1285
1286                 if (recurse || (xfer_dirs && is_dot_dir)) {
1287                         struct file_struct *file;
1288                         file = send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR);
1289                         if (file)
1290                                 send_if_directory(f, flist, file, fbuf, len);
1291                 } else
1292                         send_file_name(f, flist, fbuf, &st, 0);
1293
1294                 if (olddir[0]) {
1295                         flist_dir = NULL;
1296                         flist_dir_len = 0;
1297                         if (!pop_dir(olddir)) {
1298                                 rsyserr(FERROR, errno, "pop_dir %s failed",
1299                                         full_fname(olddir));
1300                                 exit_cleanup(RERR_FILESELECT);
1301                         }
1302                 }
1303         }
1304
1305         gettimeofday(&end_tv, NULL);
1306         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1307                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1308         if (stats.flist_buildtime == 0)
1309                 stats.flist_buildtime = 1;
1310         start_tv = end_tv;
1311
1312         send_file_entry(NULL, f);
1313
1314         if (show_filelist_p())
1315                 finish_filelist_progress(flist);
1316
1317         gettimeofday(&end_tv, NULL);
1318         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1319                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1320
1321         if (flist->hlink_pool) {
1322                 pool_destroy(flist->hlink_pool);
1323                 flist->hlink_pool = NULL;
1324         }
1325
1326         /* Sort the list without removing any duplicates.  This allows the
1327          * receiving side to ask for any name they like, which gives us the
1328          * flexibility to change the way we unduplicate names in the future
1329          * without causing a compatibility problem with older versions. */
1330         clean_flist(flist, 0, 0);
1331
1332         send_uid_list(f);
1333
1334         /* send the io_error flag */
1335         write_int(f, lp_ignore_errors(module_id) ? 0 : io_error);
1336
1337         io_end_buffering();
1338         stats.flist_size = stats.total_written - start_write;
1339         stats.num_files = flist->count;
1340
1341         if (verbose > 3)
1342                 output_flist(flist);
1343
1344         if (verbose > 2)
1345                 rprintf(FINFO, "send_file_list done\n");
1346
1347         return flist;
1348 }
1349
1350 struct file_list *recv_file_list(int f)
1351 {
1352         struct file_list *flist;
1353         unsigned short flags;
1354         int64 start_read;
1355
1356         if (show_filelist_p())
1357                 start_filelist_progress("receiving file list");
1358
1359         start_read = stats.total_read;
1360
1361         flist = flist_new(WITH_HLINK, "recv_file_list");
1362
1363         flist->count = 0;
1364         flist->malloced = 1000;
1365         flist->files = new_array(struct file_struct *, flist->malloced);
1366         if (!flist->files)
1367                 goto oom;
1368
1369         while ((flags = read_byte(f)) != 0) {
1370                 struct file_struct *file;
1371
1372                 flist_expand(flist);
1373
1374                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1375                         flags |= read_byte(f) << 8;
1376                 file = receive_file_entry(flist, flags, f);
1377
1378                 if (S_ISREG(file->mode))
1379                         stats.total_size += file->length;
1380
1381                 flist->files[flist->count++] = file;
1382
1383                 maybe_emit_filelist_progress(flist->count);
1384
1385                 if (verbose > 2) {
1386                         rprintf(FINFO, "recv_file_name(%s)\n",
1387                                 f_name(file, NULL));
1388                 }
1389         }
1390         receive_file_entry(NULL, 0, 0); /* Signal that we're done. */
1391
1392         if (verbose > 2)
1393                 rprintf(FINFO, "received %d names\n", flist->count);
1394
1395         if (show_filelist_p())
1396                 finish_filelist_progress(flist);
1397
1398         clean_flist(flist, relative_paths, 1);
1399
1400         if (f >= 0) {
1401                 recv_uid_list(f, flist);
1402
1403                 /* Recv the io_error flag */
1404                 if (lp_ignore_errors(module_id) || ignore_errors)
1405                         read_int(f);
1406                 else
1407                         io_error |= read_int(f);
1408         }
1409
1410         if (verbose > 3)
1411                 output_flist(flist);
1412
1413         if (list_only) {
1414                 int i;
1415                 for (i = 0; i < flist->count; i++)
1416                         list_file_entry(flist->files[i]);
1417         }
1418
1419         if (verbose > 2)
1420                 rprintf(FINFO, "recv_file_list done\n");
1421
1422         stats.flist_size = stats.total_read - start_read;
1423         stats.num_files = flist->count;
1424
1425         return flist;
1426
1427   oom:
1428         out_of_memory("recv_file_list");
1429         return NULL;            /* not reached */
1430 }
1431
1432 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1433 {
1434         return f_name_cmp(*file1, *file2);
1435 }
1436
1437 /* Search for an identically-named item in the file list.  Note that the
1438  * items must agree in their directory-ness, or no match is returned. */
1439 int flist_find(struct file_list *flist, struct file_struct *f)
1440 {
1441         int low = flist->low, high = flist->high;
1442         int ret, mid, mid_up;
1443
1444         while (low <= high) {
1445                 mid = (low + high) / 2;
1446                 if (flist->files[mid]->basename)
1447                         mid_up = mid;
1448                 else if (flist->files[mid]->dir.depth) {
1449                         mid_up = mid + flist->files[mid]->dir.depth;
1450                         if (mid_up < mid) {
1451                                 high = mid_up;
1452                                 continue;
1453                         }
1454                 } else {
1455                         /* Scan for the next non-empty entry and cache
1456                          * the distance so we never do this again. */
1457                         mid_up = mid;
1458                         while (++mid_up <= high
1459                             && !flist->files[mid_up]->basename) {}
1460                         if (mid_up > high) {
1461                                 high = mid;
1462                                 while (--high >= low
1463                                     && !flist->files[high]->basename) {}
1464                                 flist->files[mid]->dir.depth = high - mid;
1465                                 continue;
1466                         }
1467                         flist->files[mid]->dir.depth = mid_up - mid;
1468                 }
1469                 ret = f_name_cmp(flist->files[mid_up], f);
1470                 if (ret == 0) {
1471                         if (protocol_version < 29
1472                             && S_ISDIR(flist->files[mid_up]->mode)
1473                             != S_ISDIR(f->mode))
1474                                 return -1;
1475                         return mid_up;
1476                 }
1477                 if (ret > 0)
1478                         high = mid - 1;
1479                 else
1480                         low = mid_up + 1;
1481         }
1482         return -1;
1483 }
1484
1485 /*
1486  * Free up any resources a file_struct has allocated
1487  * and clear the file.
1488  */
1489 void clear_file(int i, struct file_list *flist)
1490 {
1491         if (flist->hlink_pool && flist->files[i]->link_u.idev)
1492                 pool_free(flist->hlink_pool, 0, flist->files[i]->link_u.idev);
1493         memset(flist->files[i], 0, file_struct_len);
1494 }
1495
1496 /*
1497  * allocate a new file list
1498  */
1499 struct file_list *flist_new(int with_hlink, char *msg)
1500 {
1501         struct file_list *flist;
1502
1503         flist = new(struct file_list);
1504         if (!flist)
1505                 out_of_memory(msg);
1506
1507         memset(flist, 0, sizeof (struct file_list));
1508
1509         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0,
1510             out_of_memory, POOL_INTERN)))
1511                 out_of_memory(msg);
1512
1513 #ifdef SUPPORT_HARD_LINKS
1514         if (with_hlink && preserve_hard_links) {
1515                 if (!(flist->hlink_pool = pool_create(HLINK_EXTENT,
1516                     sizeof (struct idev), out_of_memory, POOL_INTERN)))
1517                         out_of_memory(msg);
1518         }
1519 #endif
1520
1521         return flist;
1522 }
1523
1524 /*
1525  * free up all elements in a flist
1526  */
1527 void flist_free(struct file_list *flist)
1528 {
1529         pool_destroy(flist->file_pool);
1530         pool_destroy(flist->hlink_pool);
1531         free(flist->files);
1532         free(flist);
1533 }
1534
1535 /*
1536  * This routine ensures we don't have any duplicate names in our file list.
1537  * duplicate names can cause corruption because of the pipelining
1538  */
1539 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1540 {
1541         int i, prev_i = 0;
1542
1543         if (!flist)
1544                 return;
1545         if (flist->count == 0) {
1546                 flist->high = -1;
1547                 return;
1548         }
1549
1550         qsort(flist->files, flist->count,
1551             sizeof flist->files[0], (int (*)())file_compare);
1552
1553         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1554                 if (flist->files[i]->basename) {
1555                         prev_i = i;
1556                         break;
1557                 }
1558         }
1559         flist->low = prev_i;
1560         while (++i < flist->count) {
1561                 int j;
1562                 struct file_struct *file = flist->files[i];
1563
1564                 if (!file->basename)
1565                         continue;
1566                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1567                         j = prev_i;
1568                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1569                         int save_mode = file->mode;
1570                         /* Make sure that this directory doesn't duplicate a
1571                          * non-directory earlier in the list. */
1572                         flist->high = prev_i;
1573                         file->mode = S_IFREG;
1574                         j = flist_find(flist, file);
1575                         file->mode = save_mode;
1576                 } else
1577                         j = -1;
1578                 if (j >= 0) {
1579                         struct file_struct *fp = flist->files[j];
1580                         int keep, drop;
1581                         /* If one is a dir and the other is not, we want to
1582                          * keep the dir because it might have contents in the
1583                          * list. */
1584                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1585                                 if (S_ISDIR(file->mode))
1586                                         keep = i, drop = j;
1587                                 else
1588                                         keep = j, drop = i;
1589                         } else
1590                                 keep = j, drop = i;
1591                         if (verbose > 1 && !am_server) {
1592                                 rprintf(FINFO,
1593                                         "removing duplicate name %s from file list (%d)\n",
1594                                         f_name(file, NULL), drop);
1595                         }
1596                         /* Make sure we don't lose track of a user-specified
1597                          * top directory. */
1598                         flist->files[keep]->flags |= flist->files[drop]->flags
1599                                                    & (FLAG_TOP_DIR|FLAG_DEL_HERE);
1600
1601                         clear_file(drop, flist);
1602
1603                         if (keep == i) {
1604                                 if (flist->low == drop) {
1605                                         for (j = drop + 1;
1606                                              j < i && !flist->files[j]->basename;
1607                                              j++) {}
1608                                         flist->low = j;
1609                                 }
1610                                 prev_i = i;
1611                         }
1612                 } else
1613                         prev_i = i;
1614         }
1615         flist->high = no_dups ? prev_i : flist->count - 1;
1616
1617         if (strip_root) {
1618                 /* We need to strip off the leading slashes for relative
1619                  * paths, but this must be done _after_ the sorting phase. */
1620                 for (i = flist->low; i <= flist->high; i++) {
1621                         struct file_struct *file = flist->files[i];
1622
1623                         if (!file->dirname)
1624                                 continue;
1625                         while (*file->dirname == '/')
1626                                 file->dirname++;
1627                         if (!*file->dirname)
1628                                 file->dirname = NULL;
1629                 }
1630         }
1631
1632         if (skip_empty_dirs && no_dups && max_dir_depth) {
1633                 int j, cur_depth = 0;
1634                 int *maybe_dirs = new_array(int, max_dir_depth);
1635
1636                 maybe_dirs[0] = -1;
1637
1638                 for (i = flist->low; i <= flist->high; i++) {
1639                         struct file_struct *file = flist->files[i];
1640
1641                         if (S_ISDIR(file->mode) && file->dir.depth) {
1642                                 j = cur_depth;
1643                                 cur_depth = file->dir.depth - 1;
1644                                 for ( ; j >= cur_depth; j--) {
1645                                         if (maybe_dirs[j] < 0)
1646                                                 continue;
1647                                         clear_file(maybe_dirs[j], flist);
1648                                 }
1649                                 maybe_dirs[cur_depth] = i;
1650                         } else if (maybe_dirs[cur_depth] >= 0) {
1651                                 for (j = 0; j <= cur_depth; j++)
1652                                         maybe_dirs[j] = -1;
1653                         }
1654                 }
1655                 for (j = cur_depth; j >= 0; j--) {
1656                         if (maybe_dirs[j] < 0)
1657                                 continue;
1658                         clear_file(maybe_dirs[j], flist);
1659                 }
1660
1661                 for (i = flist->low; i <= flist->high; i++) {
1662                         if (flist->files[i]->basename)
1663                                 break;
1664                 }
1665                 flist->low = i;
1666                 for (i = flist->high; i >= flist->low; i--) {
1667                         if (flist->files[i]->basename)
1668                                 break;
1669                 }
1670                 flist->high = i;
1671         }
1672 }
1673
1674 static void output_flist(struct file_list *flist)
1675 {
1676         char uidbuf[16], gidbuf[16], depthbuf[16];
1677         struct file_struct *file;
1678         const char *who = who_am_i();
1679         int i;
1680
1681         for (i = 0; i < flist->count; i++) {
1682                 file = flist->files[i];
1683                 if ((am_root || am_sender) && preserve_uid)
1684                         sprintf(uidbuf, " uid=%ld", (long)file->uid);
1685                 else
1686                         *uidbuf = '\0';
1687                 if (preserve_gid && file->gid != GID_NONE)
1688                         sprintf(gidbuf, " gid=%ld", (long)file->gid);
1689                 else
1690                         *gidbuf = '\0';
1691                 if (!am_sender)
1692                         sprintf(depthbuf, "%d", file->dir.depth);
1693                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
1694                         who, i, am_sender ? NS(file->dir.root) : depthbuf,
1695                         file->dirname ? file->dirname : "",
1696                         file->dirname ? "/" : "", NS(file->basename),
1697                         S_ISDIR(file->mode) ? "/" : "", (int)file->mode,
1698                         (double)file->length, uidbuf, gidbuf, file->flags);
1699         }
1700 }
1701
1702 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
1703 enum fnc_type { t_PATH, t_ITEM };
1704
1705 /* Compare the names of two file_struct entities, similar to how strcmp()
1706  * would do if it were operating on the joined strings.
1707  *
1708  * Some differences beginning with protocol_version 29: (1) directory names
1709  * are compared with an assumed trailing slash so that they compare in a
1710  * way that would cause them to sort immediately prior to any content they
1711  * may have; (2) a directory of any name compares after a non-directory of
1712  * any name at the same depth; (3) a directory with name "." compares prior
1713  * to anything else.  These changes mean that a directory and a non-dir
1714  * with the same name will not compare as equal (protocol_version >= 29).
1715  *
1716  * The dirname component can be an empty string, but the basename component
1717  * cannot (and never is in the current codebase).  The basename component
1718  * may be NULL (for a removed item), in which case it is considered to be
1719  * after any existing item. */
1720 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
1721 {
1722         int dif;
1723         const uchar *c1, *c2;
1724         enum fnc_state state1, state2;
1725         enum fnc_type type1, type2;
1726         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
1727
1728         if (!f1 || !f1->basename) {
1729                 if (!f2 || !f2->basename)
1730                         return 0;
1731                 return -1;
1732         }
1733         if (!f2 || !f2->basename)
1734                 return 1;
1735
1736         c1 = (uchar*)f1->dirname;
1737         c2 = (uchar*)f2->dirname;
1738         if (c1 == c2)
1739                 c1 = c2 = NULL;
1740         if (!c1) {
1741                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1742                 c1 = (uchar*)f1->basename;
1743                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1744                         type1 = t_ITEM;
1745                         state1 = s_TRAILING;
1746                         c1 = (uchar*)"";
1747                 } else
1748                         state1 = s_BASE;
1749         } else if (!*c1) {
1750                 type1 = t_path;
1751                 state1 = s_SLASH;
1752                 c1 = (uchar*)"/";
1753         } else {
1754                 type1 = t_path;
1755                 state1 = s_DIR;
1756         }
1757         if (!c2) {
1758                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1759                 c2 = (uchar*)f2->basename;
1760                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1761                         type2 = t_ITEM;
1762                         state2 = s_TRAILING;
1763                         c2 = (uchar*)"";
1764                 } else
1765                         state2 = s_BASE;
1766         } else if (!*c2) {
1767                 type2 = t_path;
1768                 state2 = s_SLASH;
1769                 c2 = (uchar*)"/";
1770         } else {
1771                 type2 = t_path;
1772                 state2 = s_DIR;
1773         }
1774
1775         if (type1 != type2)
1776                 return type1 == t_PATH ? 1 : -1;
1777
1778         while (1) {
1779                 if ((dif = (int)*c1++ - (int)*c2++) != 0)
1780                         break;
1781                 if (!*c1) {
1782                         switch (state1) {
1783                         case s_DIR:
1784                                 state1 = s_SLASH;
1785                                 c1 = (uchar*)"/";
1786                                 break;
1787                         case s_SLASH:
1788                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1789                                 c1 = (uchar*)f1->basename;
1790                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1791                                         type1 = t_ITEM;
1792                                         state1 = s_TRAILING;
1793                                         c1 = (uchar*)"";
1794                                 } else
1795                                         state1 = s_BASE;
1796                                 break;
1797                         case s_BASE:
1798                                 state1 = s_TRAILING;
1799                                 if (type1 == t_PATH) {
1800                                         c1 = (uchar*)"/";
1801                                         break;
1802                                 }
1803                                 /* FALL THROUGH */
1804                         case s_TRAILING:
1805                                 type1 = t_ITEM;
1806                                 break;
1807                         }
1808                         if (*c2 && type1 != type2)
1809                                 return type1 == t_PATH ? 1 : -1;
1810                 }
1811                 if (!*c2) {
1812                         switch (state2) {
1813                         case s_DIR:
1814                                 state2 = s_SLASH;
1815                                 c2 = (uchar*)"/";
1816                                 break;
1817                         case s_SLASH:
1818                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1819                                 c2 = (uchar*)f2->basename;
1820                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1821                                         type2 = t_ITEM;
1822                                         state2 = s_TRAILING;
1823                                         c2 = (uchar*)"";
1824                                 } else
1825                                         state2 = s_BASE;
1826                                 break;
1827                         case s_BASE:
1828                                 state2 = s_TRAILING;
1829                                 if (type2 == t_PATH) {
1830                                         c2 = (uchar*)"/";
1831                                         break;
1832                                 }
1833                                 /* FALL THROUGH */
1834                         case s_TRAILING:
1835                                 if (!*c1)
1836                                         return 0;
1837                                 type2 = t_ITEM;
1838                                 break;
1839                         }
1840                         if (type1 != type2)
1841                                 return type1 == t_PATH ? 1 : -1;
1842                 }
1843         }
1844
1845         return dif;
1846 }
1847
1848 /* Return a copy of the full filename of a flist entry, using the indicated
1849  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
1850  * done because we checked the size when creating the file_struct entry.
1851  */
1852 char *f_name(struct file_struct *f, char *fbuf)
1853 {
1854         if (!f || !f->basename)
1855                 return NULL;
1856
1857         if (!fbuf) {
1858                 static char names[5][MAXPATHLEN];
1859                 static unsigned int n;
1860
1861                 n = (n + 1) % (sizeof names / sizeof names[0]);
1862
1863                 fbuf = names[n];
1864         }
1865
1866         if (f->dirname) {
1867                 int len = strlen(f->dirname);
1868                 memcpy(fbuf, f->dirname, len);
1869                 fbuf[len] = '/';
1870                 strcpy(fbuf + len + 1, f->basename);
1871         } else
1872                 strcpy(fbuf, f->basename);
1873
1874         return fbuf;
1875 }
1876
1877 /* Do a non-recursive scan of the named directory, possibly ignoring all
1878  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
1879  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
1880  * buffer (the functions we call will append names onto the end, but the old
1881  * dir value will be restored on exit). */
1882 struct file_list *get_dirlist(char *dirname, int dlen,
1883                               int ignore_filter_rules)
1884 {
1885         struct file_list *dirlist;
1886         char dirbuf[MAXPATHLEN];
1887         int save_recurse = recurse;
1888
1889         if (dlen < 0) {
1890                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
1891                 if (dlen >= MAXPATHLEN)
1892                         return NULL;
1893                 dirname = dirbuf;
1894         }
1895
1896         dirlist = flist_new(WITHOUT_HLINK, "get_dirlist");
1897
1898         recurse = 0;
1899         send_directory(ignore_filter_rules ? -2 : -1, dirlist, dirname, dlen);
1900         recurse = save_recurse;
1901         if (do_progress)
1902                 flist_count_offset += dirlist->count;
1903
1904         clean_flist(dirlist, 0, 0);
1905
1906         if (verbose > 3)
1907                 output_flist(dirlist);
1908
1909         return dirlist;
1910 }