Made get_dirlist() always include directories.
[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 prune_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 const char *io_write_phase;
63 extern struct stats stats;
64 extern struct file_list *the_file_list;
65
66 extern char curr_dir[MAXPATHLEN];
67
68 extern struct chmod_mode_struct *chmod_modes;
69
70 extern struct filter_list_struct filter_list;
71 extern struct filter_list_struct server_filter_list;
72
73 int io_error;
74 int checksum_len;
75 dev_t filesystem_dev; /* used to implement -x */
76 unsigned int file_struct_len;
77
78 static char empty_sum[MD4_SUM_LENGTH];
79 static int flist_count_offset;
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 permbuf[PERMSTRING_SIZE];
135
136         if (!f->basename) {
137                 /* this can happen if duplicate names were removed */
138                 return;
139         }
140
141         permstring(permbuf, 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                         permbuf,
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                         permbuf,
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         } else if (dirname) {
639                 file->dirname = dirname; /* we're reusing lastname */
640                 file->dir.depth = lastdir_depth + 1;
641         } else
642                 file->dir.depth = 1;
643
644         if (S_ISDIR(mode)) {
645                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
646                         file->dir.depth--;
647                 if (flags & XMIT_TOP_DIR) {
648                         in_del_hier = recurse;
649                         del_hier_name_len = file->dir.depth == 0 ? 0 : l1 + l2;
650                         if (relative_paths && del_hier_name_len > 2
651                             && lastname[del_hier_name_len-1] == '.'
652                             && lastname[del_hier_name_len-2] == '/')
653                                 del_hier_name_len -= 2;
654                         file->flags |= FLAG_TOP_DIR | FLAG_DEL_HERE;
655                 } else if (in_del_hier) {
656                         if (!relative_paths || !del_hier_name_len
657                          || (l1 >= del_hier_name_len
658                           && lastname[del_hier_name_len] == '/'))
659                                 file->flags |= FLAG_DEL_HERE;
660                         else
661                                 in_del_hier = 0;
662                 }
663         }
664
665         file->basename = bp;
666         memcpy(bp, basename, basename_len);
667         bp += basename_len;
668
669         if ((preserve_devices && IS_DEVICE(mode))
670          || (preserve_specials && IS_SPECIAL(mode)))
671                 file->u.rdev = rdev;
672
673 #ifdef SUPPORT_LINKS
674         if (linkname_len) {
675                 file->u.link = bp;
676                 read_sbuf(f, bp, linkname_len - 1);
677                 if (sanitize_paths)
678                         sanitize_path(bp, bp, "", lastdir_depth);
679                 bp += linkname_len;
680         }
681 #endif
682
683 #ifdef SUPPORT_HARD_LINKS
684         if (preserve_hard_links && protocol_version < 28 && S_ISREG(mode))
685                 flags |= XMIT_HAS_IDEV_DATA;
686         if (flags & XMIT_HAS_IDEV_DATA) {
687                 int64 inode;
688                 if (protocol_version < 26) {
689                         dev = read_int(f);
690                         inode = read_int(f);
691                 } else {
692                         if (!(flags & XMIT_SAME_DEV))
693                                 dev = read_longint(f);
694                         inode = read_longint(f);
695                 }
696                 if (flist->hlink_pool) {
697                         file->link_u.idev = pool_talloc(flist->hlink_pool,
698                             struct idev, 1, "inode_table");
699                         file->F_INODE = inode;
700                         file->F_DEV = dev;
701                 }
702         }
703 #endif
704
705         if (always_checksum && (sum_len || protocol_version < 28)) {
706                 char *sum;
707                 if (sum_len) {
708                         file->u.sum = sum = bp;
709                         /*bp += sum_len;*/
710                 } else {
711                         /* Prior to 28, we get a useless set of nulls. */
712                         sum = empty_sum;
713                 }
714                 read_buf(f, sum, checksum_len);
715         }
716
717         if (!preserve_perms) {
718                 /* set an appropriate set of permissions based on original
719                  * permissions and umask. This emulates what GNU cp does */
720                 file->mode &= ~orig_umask;
721         }
722
723         return file;
724 }
725
726 /**
727  * Create a file_struct for a named file by reading its stat()
728  * information and performing extensive checks against global
729  * options.
730  *
731  * @return the new file, or NULL if there was an error or this file
732  * should be excluded.
733  *
734  * @todo There is a small optimization opportunity here to avoid
735  * stat()ing the file in some circumstances, which has a certain cost.
736  * We are called immediately after doing readdir(), and so we may
737  * already know the d_type of the file.  We could for example avoid
738  * statting directories if we're not recursing, but this is not a very
739  * important case.  Some systems may not have d_type.
740  **/
741 struct file_struct *make_file(char *fname, struct file_list *flist,
742                               STRUCT_STAT *stp, unsigned short flags,
743                               int filter_level)
744 {
745         static char *lastdir;
746         static int lastdir_len = -1;
747         struct file_struct *file;
748         STRUCT_STAT st;
749         char sum[SUM_LENGTH];
750         char thisname[MAXPATHLEN];
751         char linkname[MAXPATHLEN];
752         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
753         char *basename, *dirname, *bp;
754
755         if (!flist || !flist->count)    /* Ignore lastdir when invalid. */
756                 lastdir_len = -1;
757
758         if (strlcpy(thisname, fname, sizeof thisname)
759             >= sizeof thisname - flist_dir_len) {
760                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
761                 return NULL;
762         }
763         clean_fname(thisname, 0);
764         if (sanitize_paths)
765                 sanitize_path(thisname, thisname, "", 0);
766
767         memset(sum, 0, SUM_LENGTH);
768
769         if (stp && S_ISDIR(stp->st_mode))
770                 st = *stp; /* Needed for "symlink/." with --relative. */
771         else if (readlink_stat(thisname, &st, linkname) != 0) {
772                 int save_errno = errno;
773                 /* See if file is excluded before reporting an error. */
774                 if (filter_level != NO_FILTERS
775                     && is_excluded(thisname, 0, filter_level))
776                         return NULL;
777                 if (save_errno == ENOENT) {
778 #ifdef SUPPORT_LINKS
779                         /* Avoid "vanished" error if symlink points nowhere. */
780                         if (copy_links && do_lstat(thisname, &st) == 0
781                             && S_ISLNK(st.st_mode)) {
782                                 io_error |= IOERR_GENERAL;
783                                 rprintf(FERROR, "symlink has no referent: %s\n",
784                                         full_fname(thisname));
785                         } else
786 #endif
787                         {
788                                 enum logcode c = am_daemon && protocol_version < 28
789                                     ? FERROR : FINFO;
790                                 io_error |= IOERR_VANISHED;
791                                 rprintf(c, "file has vanished: %s\n",
792                                         full_fname(thisname));
793                         }
794                 } else {
795                         io_error |= IOERR_GENERAL;
796                         rsyserr(FERROR, save_errno, "readlink %s failed",
797                                 full_fname(thisname));
798                 }
799                 return NULL;
800         }
801
802         /* backup.c calls us with filter_level set to NO_FILTERS. */
803         if (filter_level == NO_FILTERS)
804                 goto skip_filters;
805
806         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
807                 rprintf(FINFO, "skipping directory %s\n", thisname);
808                 return NULL;
809         }
810
811         /* We only care about directories because we need to avoid recursing
812          * into a mount-point directory, not to avoid copying a symlinked
813          * file if -L (or similar) was specified. */
814         if (one_file_system && st.st_dev != filesystem_dev
815          && S_ISDIR(st.st_mode)) {
816                 if (one_file_system > 1) {
817                         if (verbose > 2) {
818                                 rprintf(FINFO, "skipping mount-point dir %s\n",
819                                         thisname);
820                         }
821                         return NULL;
822                 }
823                 flags |= FLAG_MOUNT_POINT;
824         }
825
826         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level))
827                 return NULL;
828
829         if (lp_ignore_nonreadable(module_id)) {
830 #ifdef SUPPORT_LINKS
831                 if (!S_ISLNK(st.st_mode))
832 #endif
833                         if (access(thisname, R_OK) != 0)
834                                 return NULL;
835         }
836
837   skip_filters:
838
839         if (verbose > 2) {
840                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
841                         who_am_i(), thisname, filter_level);
842         }
843
844         if ((basename = strrchr(thisname, '/')) != NULL) {
845                 dirname_len = ++basename - thisname; /* counts future '\0' */
846                 if (lastdir_len == dirname_len - 1
847                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
848                         dirname = lastdir;
849                         dirname_len = 0; /* indicates no copy is needed */
850                 } else
851                         dirname = thisname;
852         } else {
853                 basename = thisname;
854                 dirname = NULL;
855                 dirname_len = 0;
856         }
857         basename_len = strlen(basename) + 1; /* count the '\0' */
858
859 #ifdef SUPPORT_LINKS
860         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
861 #else
862         linkname_len = 0;
863 #endif
864
865         sum_len = always_checksum && am_sender && S_ISREG(st.st_mode)
866                 ? MD4_SUM_LENGTH : 0;
867
868         alloc_len = file_struct_len + dirname_len + basename_len
869             + linkname_len + sum_len;
870         if (flist)
871                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
872         else {
873                 if (!(bp = new_array(char, alloc_len)))
874                         out_of_memory("make_file");
875         }
876
877         file = (struct file_struct *)bp;
878         memset(bp, 0, file_struct_len);
879         bp += file_struct_len;
880
881         file->flags = flags;
882         file->modtime = st.st_mtime;
883         file->length = st.st_size;
884         file->mode = st.st_mode;
885         file->uid = st.st_uid;
886         file->gid = st.st_gid;
887
888 #ifdef SUPPORT_HARD_LINKS
889         if (flist && flist->hlink_pool) {
890                 if (protocol_version < 28) {
891                         if (S_ISREG(st.st_mode))
892                                 file->link_u.idev = pool_talloc(
893                                     flist->hlink_pool, struct idev, 1,
894                                     "inode_table");
895                 } else {
896                         if (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
897                                 file->link_u.idev = pool_talloc(
898                                     flist->hlink_pool, struct idev, 1,
899                                     "inode_table");
900                 }
901         }
902         if (file->link_u.idev) {
903                 file->F_DEV = st.st_dev;
904                 file->F_INODE = st.st_ino;
905         }
906 #endif
907
908         if (dirname_len) {
909                 file->dirname = lastdir = bp;
910                 lastdir_len = dirname_len - 1;
911                 memcpy(bp, dirname, dirname_len - 1);
912                 bp += dirname_len;
913                 bp[-1] = '\0';
914         } else if (dirname)
915                 file->dirname = dirname;
916
917         file->basename = bp;
918         memcpy(bp, basename, basename_len);
919         bp += basename_len;
920
921 #ifdef HAVE_STRUCT_STAT_ST_RDEV
922         if ((preserve_devices && IS_DEVICE(st.st_mode))
923          || (preserve_specials && IS_SPECIAL(st.st_mode)))
924                 file->u.rdev = st.st_rdev;
925 #endif
926
927 #ifdef SUPPORT_LINKS
928         if (linkname_len) {
929                 file->u.link = bp;
930                 memcpy(bp, linkname, linkname_len);
931                 bp += linkname_len;
932         }
933 #endif
934
935         if (sum_len) {
936                 file->u.sum = bp;
937                 file_checksum(thisname, bp, st.st_size);
938                 /*bp += sum_len;*/
939         }
940
941         file->dir.root = flist_dir;
942
943         /* This code is only used by the receiver when it is building
944          * a list of files for a delete pass. */
945         if (keep_dirlinks && linkname_len && flist) {
946                 STRUCT_STAT st2;
947                 int save_mode = file->mode;
948                 file->mode = S_IFDIR; /* Find a directory with our name. */
949                 if (flist_find(the_file_list, file) >= 0
950                     && do_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
951                         file->modtime = st2.st_mtime;
952                         file->length = st2.st_size;
953                         file->mode = st2.st_mode;
954                         file->uid = st2.st_uid;
955                         file->gid = st2.st_gid;
956                         file->u.link = NULL;
957                 } else
958                         file->mode = save_mode;
959         }
960
961         if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
962                 stats.total_size += st.st_size;
963
964         return file;
965 }
966
967 static struct file_struct *send_file_name(int f, struct file_list *flist,
968                                           char *fname, STRUCT_STAT *stp,
969                                           unsigned short flags)
970 {
971         struct file_struct *file;
972
973         file = make_file(fname, flist, stp, flags,
974                          f == -2 ? SERVER_FILTERS : ALL_FILTERS);
975         if (!file)
976                 return NULL;
977
978         if (chmod_modes && !S_ISLNK(file->mode))
979                 file->mode = tweak_mode(file->mode, chmod_modes);
980
981         maybe_emit_filelist_progress(flist->count + flist_count_offset);
982
983         flist_expand(flist);
984
985         if (file->basename[0]) {
986                 flist->files[flist->count++] = file;
987                 send_file_entry(file, f);
988         }
989         return file;
990 }
991
992 static void send_if_directory(int f, struct file_list *flist,
993                               struct file_struct *file,
994                               char *fbuf, unsigned int ol)
995 {
996         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
997
998         if (S_ISDIR(file->mode)
999             && !(file->flags & FLAG_MOUNT_POINT) && f_name(file, fbuf)) {
1000                 void *save_filters;
1001                 unsigned int len = strlen(fbuf);
1002                 if (len > 1 && fbuf[len-1] == '/')
1003                         fbuf[--len] = '\0';
1004                 if (len >= MAXPATHLEN - 1) {
1005                         io_error |= IOERR_GENERAL;
1006                         rprintf(FERROR, "skipping long-named directory: %s\n",
1007                                 full_fname(fbuf));
1008                         return;
1009                 }
1010                 save_filters = push_local_filters(fbuf, len);
1011                 send_directory(f, flist, fbuf, len);
1012                 pop_local_filters(save_filters);
1013                 fbuf[ol] = '\0';
1014                 if (is_dot_dir)
1015                         fbuf[ol-1] = '.';
1016         }
1017 }
1018
1019 /* This function is normally called by the sender, but the receiving side also
1020  * calls it from get_dirlist() with f set to -1 so that we just construct the
1021  * file list in memory without sending it over the wire.  Also, get_dirlist()
1022  * might call this with f set to -2, which also indicates that local filter
1023  * rules should be ignored. */
1024 static void send_directory(int f, struct file_list *flist,
1025                            char *fbuf, int len)
1026 {
1027         struct dirent *di;
1028         unsigned remainder;
1029         char *p;
1030         DIR *d;
1031         int start = flist->count;
1032
1033         if (!(d = opendir(fbuf))) {
1034                 io_error |= IOERR_GENERAL;
1035                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1036                 return;
1037         }
1038
1039         p = fbuf + len;
1040         if (len != 1 || *fbuf != '/')
1041                 *p++ = '/';
1042         *p = '\0';
1043         remainder = MAXPATHLEN - (p - fbuf);
1044
1045         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1046                 char *dname = d_name(di);
1047                 if (dname[0] == '.' && (dname[1] == '\0'
1048                     || (dname[1] == '.' && dname[2] == '\0')))
1049                         continue;
1050                 if (strlcpy(p, dname, remainder) >= remainder) {
1051                         io_error |= IOERR_GENERAL;
1052                         rprintf(FINFO,
1053                                 "cannot send long-named file %s\n",
1054                                 full_fname(fbuf));
1055                         continue;
1056                 }
1057
1058                 send_file_name(f, flist, fbuf, NULL, 0);
1059         }
1060
1061         fbuf[len] = '\0';
1062
1063         if (errno) {
1064                 io_error |= IOERR_GENERAL;
1065                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1066         }
1067
1068         closedir(d);
1069
1070         if (recurse) {
1071                 int i, end = flist->count - 1;
1072                 for (i = start; i <= end; i++)
1073                         send_if_directory(f, flist, flist->files[i], fbuf, len);
1074         }
1075 }
1076
1077 struct file_list *send_file_list(int f, int argc, char *argv[])
1078 {
1079         int len;
1080         STRUCT_STAT st;
1081         char *p, *dir, olddir[sizeof curr_dir];
1082         char lastpath[MAXPATHLEN] = "";
1083         struct file_list *flist;
1084         struct timeval start_tv, end_tv;
1085         int64 start_write;
1086         int use_ff_fd = 0;
1087
1088         if (show_filelist_p())
1089                 start_filelist_progress("building file list");
1090
1091         start_write = stats.total_written;
1092         gettimeofday(&start_tv, NULL);
1093
1094         flist = flist_new(WITH_HLINK, "send_file_list");
1095
1096         io_start_buffering_out();
1097         if (filesfrom_fd >= 0) {
1098                 if (argv[0] && !push_dir(argv[0])) {
1099                         rsyserr(FERROR, errno, "push_dir %s failed",
1100                                 full_fname(argv[0]));
1101                         exit_cleanup(RERR_FILESELECT);
1102                 }
1103                 use_ff_fd = 1;
1104         }
1105
1106         while (1) {
1107                 char fbuf[MAXPATHLEN];
1108                 char *fn;
1109                 int is_dot_dir;
1110
1111                 if (use_ff_fd) {
1112                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1113                                 break;
1114                         sanitize_path(fbuf, fbuf, "", 0);
1115                 } else {
1116                         if (argc-- == 0)
1117                                 break;
1118                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1119                         if (sanitize_paths)
1120                                 sanitize_path(fbuf, fbuf, "", 0);
1121                 }
1122
1123                 len = strlen(fbuf);
1124                 if (relative_paths) {
1125                         /* We clean up fbuf below. */
1126                         is_dot_dir = 0;
1127                 } else if (!len || fbuf[len - 1] == '/') {
1128                         if (len == 2 && fbuf[0] == '.') {
1129                                 /* Turn "./" into just "." rather than "./." */
1130                                 fbuf[1] = '\0';
1131                         } else {
1132                                 if (len + 1 >= MAXPATHLEN)
1133                                         overflow_exit("send_file_list");
1134                                 fbuf[len++] = '.';
1135                                 fbuf[len] = '\0';
1136                         }
1137                         is_dot_dir = 1;
1138                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1139                     && (len == 2 || fbuf[len-3] == '/')) {
1140                         if (len + 2 >= MAXPATHLEN)
1141                                 overflow_exit("send_file_list");
1142                         fbuf[len++] = '/';
1143                         fbuf[len++] = '.';
1144                         fbuf[len] = '\0';
1145                         is_dot_dir = 1;
1146                 } else {
1147                         is_dot_dir = fbuf[len-1] == '.'
1148                                    && (len == 1 || fbuf[len-2] == '/');
1149                 }
1150
1151                 if (link_stat(fbuf, &st, keep_dirlinks) != 0) {
1152                         io_error |= IOERR_GENERAL;
1153                         rsyserr(FERROR, errno, "link_stat %s failed",
1154                                 full_fname(fbuf));
1155                         continue;
1156                 }
1157
1158                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1159                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1160                         continue;
1161                 }
1162
1163                 dir = NULL;
1164                 olddir[0] = '\0';
1165
1166                 if (!relative_paths) {
1167                         p = strrchr(fbuf, '/');
1168                         if (p) {
1169                                 *p = '\0';
1170                                 if (p == fbuf)
1171                                         dir = "/";
1172                                 else
1173                                         dir = fbuf;
1174                                 len -= p - fbuf + 1;
1175                                 fn = p + 1;
1176                         } else
1177                                 fn = fbuf;
1178                 } else {
1179                         if ((p = strstr(fbuf, "/./")) != NULL) {
1180                                 *p = '\0';
1181                                 if (p == fbuf)
1182                                         dir = "/";
1183                                 else
1184                                         dir = fbuf;
1185                                 len -= p - fbuf + 3;
1186                                 fn = p + 3;
1187                         } else
1188                                 fn = fbuf;
1189                         /* Get rid of trailing "/" and "/.". */
1190                         while (len) {
1191                                 if (fn[len - 1] == '/') {
1192                                         is_dot_dir = 1;
1193                                         if (!--len && !dir) {
1194                                                 len++;
1195                                                 break;
1196                                         }
1197                                 }
1198                                 else if (len >= 2 && fn[len - 1] == '.'
1199                                                   && fn[len - 2] == '/') {
1200                                         is_dot_dir = 1;
1201                                         if (!(len -= 2) && !dir) {
1202                                                 len++;
1203                                                 break;
1204                                         }
1205                                 } else
1206                                         break;
1207                         }
1208                         fn[len] = '\0';
1209                         /* Reject a ".." dir in the active part of the path. */
1210                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1211                                 if ((p[2] == '/' || p[2] == '\0')
1212                                  && (p == fn || p[-1] == '/')) {
1213                                         rprintf(FERROR,
1214                                             "found \"..\" dir in relative path: %s\n",
1215                                             fbuf);
1216                                         exit_cleanup(RERR_SYNTAX);
1217                                 }
1218                         }
1219                 }
1220
1221                 if (!*fn) {
1222                         len = 1;
1223                         fn = ".";
1224                 }
1225
1226                 if (dir && *dir) {
1227                         static char *lastdir;
1228                         static int lastdir_len;
1229
1230                         strlcpy(olddir, curr_dir, sizeof olddir);
1231
1232                         if (!push_dir(dir)) {
1233                                 io_error |= IOERR_GENERAL;
1234                                 rsyserr(FERROR, errno, "push_dir %s failed",
1235                                         full_fname(dir));
1236                                 continue;
1237                         }
1238
1239                         if (lastdir && strcmp(lastdir, dir) == 0) {
1240                                 flist_dir = lastdir;
1241                                 flist_dir_len = lastdir_len;
1242                         } else {
1243                                 flist_dir = lastdir = strdup(dir);
1244                                 flist_dir_len = lastdir_len = strlen(dir);
1245                         }
1246                 }
1247
1248                 if (fn != fbuf)
1249                         memmove(fbuf, fn, len + 1);
1250
1251                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1252                         /* Send the implied directories at the start of the
1253                          * source spec, so we get their permissions right. */
1254                         char *lp = lastpath, *slash = fbuf;
1255                         *p = '\0';
1256                         /* Skip any initial directories in our path that we
1257                          * have in common with lastpath. */
1258                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1259                                 if (*fn == '/')
1260                                         slash = fn;
1261                         }
1262                         *p = '/';
1263                         if (fn != p || (*lp && *lp != '/')) {
1264                                 int save_copy_links = copy_links;
1265                                 int save_xfer_dirs = xfer_dirs;
1266                                 copy_links = copy_unsafe_links;
1267                                 xfer_dirs = 1;
1268                                 while ((slash = strchr(slash+1, '/')) != 0) {
1269                                         *slash = '\0';
1270                                         send_file_name(f, flist, fbuf, NULL, 0);
1271                                         *slash = '/';
1272                                 }
1273                                 copy_links = save_copy_links;
1274                                 xfer_dirs = save_xfer_dirs;
1275                                 *p = '\0';
1276                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1277                                 *p = '/';
1278                         }
1279                 }
1280
1281                 if (one_file_system)
1282                         filesystem_dev = st.st_dev;
1283
1284                 if (recurse || (xfer_dirs && is_dot_dir)) {
1285                         struct file_struct *file;
1286                         file = send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR);
1287                         if (file)
1288                                 send_if_directory(f, flist, file, fbuf, len);
1289                 } else
1290                         send_file_name(f, flist, fbuf, &st, 0);
1291
1292                 if (olddir[0]) {
1293                         flist_dir = NULL;
1294                         flist_dir_len = 0;
1295                         if (!pop_dir(olddir)) {
1296                                 rsyserr(FERROR, errno, "pop_dir %s failed",
1297                                         full_fname(olddir));
1298                                 exit_cleanup(RERR_FILESELECT);
1299                         }
1300                 }
1301         }
1302
1303         gettimeofday(&end_tv, NULL);
1304         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1305                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1306         if (stats.flist_buildtime == 0)
1307                 stats.flist_buildtime = 1;
1308         start_tv = end_tv;
1309
1310         send_file_entry(NULL, f);
1311
1312         if (show_filelist_p())
1313                 finish_filelist_progress(flist);
1314
1315         gettimeofday(&end_tv, NULL);
1316         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1317                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1318
1319         if (flist->hlink_pool) {
1320                 pool_destroy(flist->hlink_pool);
1321                 flist->hlink_pool = NULL;
1322         }
1323
1324         /* Sort the list without removing any duplicates.  This allows the
1325          * receiving side to ask for any name they like, which gives us the
1326          * flexibility to change the way we unduplicate names in the future
1327          * without causing a compatibility problem with older versions. */
1328         clean_flist(flist, 0, 0);
1329
1330         send_uid_list(f);
1331
1332         /* send the io_error flag */
1333         write_int(f, lp_ignore_errors(module_id) ? 0 : io_error);
1334
1335         io_end_buffering();
1336         stats.flist_size = stats.total_written - start_write;
1337         stats.num_files = flist->count;
1338
1339         if (verbose > 3)
1340                 output_flist(flist);
1341
1342         if (verbose > 2)
1343                 rprintf(FINFO, "send_file_list done\n");
1344
1345         return flist;
1346 }
1347
1348 struct file_list *recv_file_list(int f)
1349 {
1350         struct file_list *flist;
1351         unsigned short flags;
1352         int64 start_read;
1353
1354         if (show_filelist_p())
1355                 start_filelist_progress("receiving file list");
1356
1357         start_read = stats.total_read;
1358
1359         flist = flist_new(WITH_HLINK, "recv_file_list");
1360
1361         flist->count = 0;
1362         flist->malloced = 1000;
1363         flist->files = new_array(struct file_struct *, flist->malloced);
1364         if (!flist->files)
1365                 goto oom;
1366
1367         while ((flags = read_byte(f)) != 0) {
1368                 struct file_struct *file;
1369
1370                 flist_expand(flist);
1371
1372                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1373                         flags |= read_byte(f) << 8;
1374                 file = receive_file_entry(flist, flags, f);
1375
1376                 if (S_ISREG(file->mode))
1377                         stats.total_size += file->length;
1378
1379                 flist->files[flist->count++] = file;
1380
1381                 maybe_emit_filelist_progress(flist->count);
1382
1383                 if (verbose > 2) {
1384                         rprintf(FINFO, "recv_file_name(%s)\n",
1385                                 f_name(file, NULL));
1386                 }
1387         }
1388         receive_file_entry(NULL, 0, 0); /* Signal that we're done. */
1389
1390         if (verbose > 2)
1391                 rprintf(FINFO, "received %d names\n", flist->count);
1392
1393         if (show_filelist_p())
1394                 finish_filelist_progress(flist);
1395
1396         clean_flist(flist, relative_paths, 1);
1397
1398         if (f >= 0) {
1399                 recv_uid_list(f, flist);
1400
1401                 /* Recv the io_error flag */
1402                 if (lp_ignore_errors(module_id) || ignore_errors)
1403                         read_int(f);
1404                 else
1405                         io_error |= read_int(f);
1406         }
1407
1408         if (verbose > 3)
1409                 output_flist(flist);
1410
1411         if (list_only) {
1412                 int i;
1413                 for (i = 0; i < flist->count; i++)
1414                         list_file_entry(flist->files[i]);
1415         }
1416
1417         if (verbose > 2)
1418                 rprintf(FINFO, "recv_file_list done\n");
1419
1420         stats.flist_size = stats.total_read - start_read;
1421         stats.num_files = flist->count;
1422
1423         return flist;
1424
1425   oom:
1426         out_of_memory("recv_file_list");
1427         return NULL;            /* not reached */
1428 }
1429
1430 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1431 {
1432         return f_name_cmp(*file1, *file2);
1433 }
1434
1435 /* Search for an identically-named item in the file list.  Note that the
1436  * items must agree in their directory-ness, or no match is returned. */
1437 int flist_find(struct file_list *flist, struct file_struct *f)
1438 {
1439         int low = flist->low, high = flist->high;
1440         int diff, mid, mid_up;
1441
1442         while (low <= high) {
1443                 mid = (low + high) / 2;
1444                 if (flist->files[mid]->basename)
1445                         mid_up = mid;
1446                 else {
1447                         /* Scan for the next non-empty entry using the cached
1448                          * distance values.  If the value isn't fully up-to-
1449                          * date, update it. */
1450                         mid_up = mid + flist->files[mid]->dir.depth;
1451                         if (!flist->files[mid_up]->basename) {
1452                                 do {
1453                                     mid_up += flist->files[mid_up]->dir.depth;
1454                                 } while (!flist->files[mid_up]->basename);
1455                                 flist->files[mid]->dir.depth = mid_up - mid;
1456                         }
1457                         if (mid_up > high) {
1458                                 /* If there's nothing left above us, set high to
1459                                  * a non-empty entry below us and continue. */
1460                                 high = mid - flist->files[mid]->length;
1461                                 if (!flist->files[high]->basename) {
1462                                         do {
1463                                             high -= flist->files[high]->length;
1464                                         } while (!flist->files[high]->basename);
1465                                         flist->files[mid]->length = mid - high;
1466                                 }
1467                                 continue;
1468                         }
1469                 }
1470                 diff = f_name_cmp(flist->files[mid_up], f);
1471                 if (diff == 0) {
1472                         if (protocol_version < 29
1473                             && S_ISDIR(flist->files[mid_up]->mode)
1474                             != S_ISDIR(f->mode))
1475                                 return -1;
1476                         return mid_up;
1477                 }
1478                 if (diff < 0)
1479                         low = mid_up + 1;
1480                 else
1481                         high = mid - 1;
1482         }
1483         return -1;
1484 }
1485
1486 /*
1487  * Free up any resources a file_struct has allocated
1488  * and clear the file.
1489  */
1490 void clear_file(struct file_struct *file, struct file_list *flist)
1491 {
1492         if (flist->hlink_pool && file->link_u.idev)
1493                 pool_free(flist->hlink_pool, 0, file->link_u.idev);
1494         memset(file, 0, file_struct_len);
1495         /* In an empty entry, dir.depth is an offset to the next non-empty
1496          * entry.  Likewise for length in the opposite direction.  We assume
1497          * that we're alone for now since flist_find() will collate adjacent
1498          * items for any entries that are encountered during the find. */
1499         file->length = file->dir.depth = 1;
1500 }
1501
1502 /*
1503  * allocate a new file list
1504  */
1505 struct file_list *flist_new(int with_hlink, char *msg)
1506 {
1507         struct file_list *flist;
1508
1509         flist = new(struct file_list);
1510         if (!flist)
1511                 out_of_memory(msg);
1512
1513         memset(flist, 0, sizeof (struct file_list));
1514
1515         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0,
1516             out_of_memory, POOL_INTERN)))
1517                 out_of_memory(msg);
1518
1519 #ifdef SUPPORT_HARD_LINKS
1520         if (with_hlink && preserve_hard_links) {
1521                 if (!(flist->hlink_pool = pool_create(HLINK_EXTENT,
1522                     sizeof (struct idev), out_of_memory, POOL_INTERN)))
1523                         out_of_memory(msg);
1524         }
1525 #endif
1526
1527         return flist;
1528 }
1529
1530 /*
1531  * free up all elements in a flist
1532  */
1533 void flist_free(struct file_list *flist)
1534 {
1535         pool_destroy(flist->file_pool);
1536         pool_destroy(flist->hlink_pool);
1537         free(flist->files);
1538         free(flist);
1539 }
1540
1541 /*
1542  * This routine ensures we don't have any duplicate names in our file list.
1543  * duplicate names can cause corruption because of the pipelining
1544  */
1545 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1546 {
1547         char fbuf[MAXPATHLEN];
1548         int i, prev_i = 0;
1549
1550         if (!flist)
1551                 return;
1552         if (flist->count == 0) {
1553                 flist->high = -1;
1554                 return;
1555         }
1556
1557         qsort(flist->files, flist->count,
1558             sizeof flist->files[0], (int (*)())file_compare);
1559
1560         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1561                 if (flist->files[i]->basename) {
1562                         prev_i = i;
1563                         break;
1564                 }
1565         }
1566         flist->low = prev_i;
1567         while (++i < flist->count) {
1568                 int j;
1569                 struct file_struct *file = flist->files[i];
1570
1571                 if (!file->basename)
1572                         continue;
1573                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1574                         j = prev_i;
1575                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1576                         int save_mode = file->mode;
1577                         /* Make sure that this directory doesn't duplicate a
1578                          * non-directory earlier in the list. */
1579                         flist->high = prev_i;
1580                         file->mode = S_IFREG;
1581                         j = flist_find(flist, file);
1582                         file->mode = save_mode;
1583                 } else
1584                         j = -1;
1585                 if (j >= 0) {
1586                         struct file_struct *fp = flist->files[j];
1587                         int keep, drop;
1588                         /* If one is a dir and the other is not, we want to
1589                          * keep the dir because it might have contents in the
1590                          * list. */
1591                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1592                                 if (S_ISDIR(file->mode))
1593                                         keep = i, drop = j;
1594                                 else
1595                                         keep = j, drop = i;
1596                         } else
1597                                 keep = j, drop = i;
1598                         if (verbose > 1 && !am_server) {
1599                                 rprintf(FINFO,
1600                                         "removing duplicate name %s from file list (%d)\n",
1601                                         f_name(file, fbuf), drop);
1602                         }
1603                         /* Make sure we don't lose track of a user-specified
1604                          * top directory. */
1605                         flist->files[keep]->flags |= flist->files[drop]->flags
1606                                                    & (FLAG_TOP_DIR|FLAG_DEL_HERE);
1607
1608                         clear_file(flist->files[drop], flist);
1609
1610                         if (keep == i) {
1611                                 if (flist->low == drop) {
1612                                         for (j = drop + 1;
1613                                              j < i && !flist->files[j]->basename;
1614                                              j++) {}
1615                                         flist->low = j;
1616                                 }
1617                                 prev_i = i;
1618                         }
1619                 } else
1620                         prev_i = i;
1621         }
1622         flist->high = no_dups ? prev_i : flist->count - 1;
1623
1624         if (strip_root) {
1625                 /* We need to strip off the leading slashes for relative
1626                  * paths, but this must be done _after_ the sorting phase. */
1627                 for (i = flist->low; i <= flist->high; i++) {
1628                         struct file_struct *file = flist->files[i];
1629
1630                         if (!file->dirname)
1631                                 continue;
1632                         while (*file->dirname == '/')
1633                                 file->dirname++;
1634                         if (!*file->dirname)
1635                                 file->dirname = NULL;
1636                 }
1637         }
1638
1639         if (prune_empty_dirs && no_dups) {
1640                 int j, prev_depth = 0;
1641
1642                 prev_i = 0; /* It's OK that this isn't really true. */
1643
1644                 for (i = flist->low; i <= flist->high; i++) {
1645                         struct file_struct *fp, *file = flist->files[i];
1646
1647                         /* This temporarily abuses the dir.depth value for a
1648                          * directory that is in a chain that might get pruned.
1649                          * We restore the old value if it gets a reprieve. */
1650                         if (S_ISDIR(file->mode) && file->dir.depth) {
1651                                 /* Dump empty dirs when coming back down. */
1652                                 for (j = prev_depth; j >= file->dir.depth; j--) {
1653                                         fp = flist->files[prev_i];
1654                                         if (fp->dir.depth >= 0)
1655                                                 break;
1656                                         prev_i = -fp->dir.depth-1;
1657                                         clear_file(fp, flist);
1658                                 }
1659                                 prev_depth = file->dir.depth;
1660                                 if (is_excluded(f_name(file, fbuf), 1,
1661                                                        ALL_FILTERS)) {
1662                                         /* Keep dirs through this dir. */
1663                                         for (j = prev_depth-1; ; j--) {
1664                                                 fp = flist->files[prev_i];
1665                                                 if (fp->dir.depth >= 0)
1666                                                         break;
1667                                                 prev_i = -fp->dir.depth-1;
1668                                                 fp->dir.depth = j;
1669                                         }
1670                                 } else
1671                                         file->dir.depth = -prev_i-1;
1672                                 prev_i = i;
1673                         } else {
1674                                 /* Keep dirs through this non-dir. */
1675                                 for (j = prev_depth; ; j--) {
1676                                         fp = flist->files[prev_i];
1677                                         if (fp->dir.depth >= 0)
1678                                                 break;
1679                                         prev_i = -fp->dir.depth-1;
1680                                         fp->dir.depth = j;
1681                                 }
1682                         }
1683                 }
1684                 /* Dump empty all remaining empty dirs. */
1685                 while (1) {
1686                         struct file_struct *fp = flist->files[prev_i];
1687                         if (fp->dir.depth >= 0)
1688                                 break;
1689                         prev_i = -fp->dir.depth-1;
1690                         clear_file(fp, flist);
1691                 }
1692
1693                 for (i = flist->low; i <= flist->high; i++) {
1694                         if (flist->files[i]->basename)
1695                                 break;
1696                 }
1697                 flist->low = i;
1698                 for (i = flist->high; i >= flist->low; i--) {
1699                         if (flist->files[i]->basename)
1700                                 break;
1701                 }
1702                 flist->high = i;
1703         }
1704 }
1705
1706 static void output_flist(struct file_list *flist)
1707 {
1708         char uidbuf[16], gidbuf[16], depthbuf[16];
1709         struct file_struct *file;
1710         const char *who = who_am_i();
1711         int i;
1712
1713         for (i = 0; i < flist->count; i++) {
1714                 file = flist->files[i];
1715                 if ((am_root || am_sender) && preserve_uid)
1716                         sprintf(uidbuf, " uid=%ld", (long)file->uid);
1717                 else
1718                         *uidbuf = '\0';
1719                 if (preserve_gid && file->gid != GID_NONE)
1720                         sprintf(gidbuf, " gid=%ld", (long)file->gid);
1721                 else
1722                         *gidbuf = '\0';
1723                 if (!am_sender)
1724                         sprintf(depthbuf, "%d", file->dir.depth);
1725                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
1726                         who, i, am_sender ? NS(file->dir.root) : depthbuf,
1727                         file->dirname ? file->dirname : "",
1728                         file->dirname ? "/" : "", NS(file->basename),
1729                         S_ISDIR(file->mode) ? "/" : "", (int)file->mode,
1730                         (double)file->length, uidbuf, gidbuf, file->flags);
1731         }
1732 }
1733
1734 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
1735 enum fnc_type { t_PATH, t_ITEM };
1736
1737 /* Compare the names of two file_struct entities, similar to how strcmp()
1738  * would do if it were operating on the joined strings.
1739  *
1740  * Some differences beginning with protocol_version 29: (1) directory names
1741  * are compared with an assumed trailing slash so that they compare in a
1742  * way that would cause them to sort immediately prior to any content they
1743  * may have; (2) a directory of any name compares after a non-directory of
1744  * any name at the same depth; (3) a directory with name "." compares prior
1745  * to anything else.  These changes mean that a directory and a non-dir
1746  * with the same name will not compare as equal (protocol_version >= 29).
1747  *
1748  * The dirname component can be an empty string, but the basename component
1749  * cannot (and never is in the current codebase).  The basename component
1750  * may be NULL (for a removed item), in which case it is considered to be
1751  * after any existing item. */
1752 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
1753 {
1754         int dif;
1755         const uchar *c1, *c2;
1756         enum fnc_state state1, state2;
1757         enum fnc_type type1, type2;
1758         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
1759
1760         if (!f1 || !f1->basename) {
1761                 if (!f2 || !f2->basename)
1762                         return 0;
1763                 return -1;
1764         }
1765         if (!f2 || !f2->basename)
1766                 return 1;
1767
1768         c1 = (uchar*)f1->dirname;
1769         c2 = (uchar*)f2->dirname;
1770         if (c1 == c2)
1771                 c1 = c2 = NULL;
1772         if (!c1) {
1773                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1774                 c1 = (uchar*)f1->basename;
1775                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1776                         type1 = t_ITEM;
1777                         state1 = s_TRAILING;
1778                         c1 = (uchar*)"";
1779                 } else
1780                         state1 = s_BASE;
1781         } else if (!*c1) {
1782                 type1 = t_path;
1783                 state1 = s_SLASH;
1784                 c1 = (uchar*)"/";
1785         } else {
1786                 type1 = t_path;
1787                 state1 = s_DIR;
1788         }
1789         if (!c2) {
1790                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1791                 c2 = (uchar*)f2->basename;
1792                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1793                         type2 = t_ITEM;
1794                         state2 = s_TRAILING;
1795                         c2 = (uchar*)"";
1796                 } else
1797                         state2 = s_BASE;
1798         } else if (!*c2) {
1799                 type2 = t_path;
1800                 state2 = s_SLASH;
1801                 c2 = (uchar*)"/";
1802         } else {
1803                 type2 = t_path;
1804                 state2 = s_DIR;
1805         }
1806
1807         if (type1 != type2)
1808                 return type1 == t_PATH ? 1 : -1;
1809
1810         while (1) {
1811                 if ((dif = (int)*c1++ - (int)*c2++) != 0)
1812                         break;
1813                 if (!*c1) {
1814                         switch (state1) {
1815                         case s_DIR:
1816                                 state1 = s_SLASH;
1817                                 c1 = (uchar*)"/";
1818                                 break;
1819                         case s_SLASH:
1820                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1821                                 c1 = (uchar*)f1->basename;
1822                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1823                                         type1 = t_ITEM;
1824                                         state1 = s_TRAILING;
1825                                         c1 = (uchar*)"";
1826                                 } else
1827                                         state1 = s_BASE;
1828                                 break;
1829                         case s_BASE:
1830                                 state1 = s_TRAILING;
1831                                 if (type1 == t_PATH) {
1832                                         c1 = (uchar*)"/";
1833                                         break;
1834                                 }
1835                                 /* FALL THROUGH */
1836                         case s_TRAILING:
1837                                 type1 = t_ITEM;
1838                                 break;
1839                         }
1840                         if (*c2 && type1 != type2)
1841                                 return type1 == t_PATH ? 1 : -1;
1842                 }
1843                 if (!*c2) {
1844                         switch (state2) {
1845                         case s_DIR:
1846                                 state2 = s_SLASH;
1847                                 c2 = (uchar*)"/";
1848                                 break;
1849                         case s_SLASH:
1850                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1851                                 c2 = (uchar*)f2->basename;
1852                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1853                                         type2 = t_ITEM;
1854                                         state2 = s_TRAILING;
1855                                         c2 = (uchar*)"";
1856                                 } else
1857                                         state2 = s_BASE;
1858                                 break;
1859                         case s_BASE:
1860                                 state2 = s_TRAILING;
1861                                 if (type2 == t_PATH) {
1862                                         c2 = (uchar*)"/";
1863                                         break;
1864                                 }
1865                                 /* FALL THROUGH */
1866                         case s_TRAILING:
1867                                 if (!*c1)
1868                                         return 0;
1869                                 type2 = t_ITEM;
1870                                 break;
1871                         }
1872                         if (type1 != type2)
1873                                 return type1 == t_PATH ? 1 : -1;
1874                 }
1875         }
1876
1877         return dif;
1878 }
1879
1880 /* Return a copy of the full filename of a flist entry, using the indicated
1881  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
1882  * done because we checked the size when creating the file_struct entry.
1883  */
1884 char *f_name(struct file_struct *f, char *fbuf)
1885 {
1886         if (!f || !f->basename)
1887                 return NULL;
1888
1889         if (!fbuf) {
1890                 static char names[5][MAXPATHLEN];
1891                 static unsigned int n;
1892
1893                 n = (n + 1) % (sizeof names / sizeof names[0]);
1894
1895                 fbuf = names[n];
1896         }
1897
1898         if (f->dirname) {
1899                 int len = strlen(f->dirname);
1900                 memcpy(fbuf, f->dirname, len);
1901                 fbuf[len] = '/';
1902                 strcpy(fbuf + len + 1, f->basename);
1903         } else
1904                 strcpy(fbuf, f->basename);
1905
1906         return fbuf;
1907 }
1908
1909 /* Do a non-recursive scan of the named directory, possibly ignoring all
1910  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
1911  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
1912  * buffer (the functions we call will append names onto the end, but the old
1913  * dir value will be restored on exit). */
1914 struct file_list *get_dirlist(char *dirname, int dlen,
1915                               int ignore_filter_rules)
1916 {
1917         struct file_list *dirlist;
1918         char dirbuf[MAXPATHLEN];
1919         int save_recurse = recurse;
1920         int save_xfer_dirs = xfer_dirs;
1921
1922         if (dlen < 0) {
1923                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
1924                 if (dlen >= MAXPATHLEN)
1925                         return NULL;
1926                 dirname = dirbuf;
1927         }
1928
1929         dirlist = flist_new(WITHOUT_HLINK, "get_dirlist");
1930
1931         recurse = 0;
1932         xfer_dirs = 1;
1933         send_directory(ignore_filter_rules ? -2 : -1, dirlist, dirname, dlen);
1934         xfer_dirs = save_xfer_dirs;
1935         recurse = save_recurse;
1936         if (do_progress)
1937                 flist_count_offset += dirlist->count;
1938
1939         clean_flist(dirlist, 0, 0);
1940
1941         if (verbose > 3)
1942                 output_flist(dirlist);
1943
1944         return dirlist;
1945 }