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