ed2393016ee1c2c7d78a37e33e53d26e9de45f04
[rsync/rsync.git] / flist.c
1 /*
2  * Generate and receive file lists.
3  *
4  * Copyright (C) 1996 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2002-2007 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
21  */
22
23 #include "rsync.h"
24 #include "rounding.h"
25 #include "io.h"
26
27 extern int verbose;
28 extern int list_only;
29 extern int am_root;
30 extern int am_server;
31 extern int am_daemon;
32 extern int am_sender;
33 extern int inc_recurse;
34 extern int do_progress;
35 extern int always_checksum;
36 extern int module_id;
37 extern int ignore_errors;
38 extern int numeric_ids;
39 extern int recurse;
40 extern int xfer_dirs;
41 extern int filesfrom_fd;
42 extern int one_file_system;
43 extern int copy_dirlinks;
44 extern int keep_dirlinks;
45 extern int preserve_acls;
46 extern int preserve_links;
47 extern int preserve_hard_links;
48 extern int preserve_devices;
49 extern int preserve_specials;
50 extern int preserve_uid;
51 extern int preserve_gid;
52 extern int relative_paths;
53 extern int implied_dirs;
54 extern int file_extra_cnt;
55 extern int ignore_perishable;
56 extern int non_perishable_cnt;
57 extern int prune_empty_dirs;
58 extern int copy_links;
59 extern int copy_unsafe_links;
60 extern int protocol_version;
61 extern int sanitize_paths;
62 extern struct stats stats;
63
64 extern char curr_dir[MAXPATHLEN];
65
66 extern struct chmod_mode_struct *chmod_modes;
67
68 extern struct filter_list_struct filter_list;
69 extern struct filter_list_struct server_filter_list;
70
71 int io_error;
72 int checksum_len;
73 dev_t filesystem_dev; /* used to implement -x */
74
75 struct file_list *cur_flist, *first_flist, *dir_flist;
76 int send_dir_ndx = -1, send_dir_depth = 0;
77 int flist_cnt = 0; /* how many (non-tmp) file list objects exist */
78 int file_total = 0; /* total of all active items over all file-lists */
79 int flist_eof = 0; /* all the file-lists are now known */
80
81 /* The tmp_* vars are used as a cache area by make_file() to store data
82  * that the sender doesn't need to remember in its file list.  The data
83  * will survive just long enough to be used by send_file_entry(). */
84 static dev_t tmp_rdev;
85 #ifdef SUPPORT_HARD_LINKS
86 static int64 tmp_dev, tmp_ino;
87 #endif
88 static char tmp_sum[MD4_SUM_LENGTH];
89
90 static char empty_sum[MD4_SUM_LENGTH];
91 static int flist_count_offset; /* for --delete --progress */
92
93 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
94 static void output_flist(struct file_list *flist);
95
96 void init_flist(void)
97 {
98         if (verbose > 4) {
99                 rprintf(FINFO, "FILE_STRUCT_LEN=%d, EXTRA_LEN=%d\n",
100                         (int)FILE_STRUCT_LEN, (int)EXTRA_LEN);
101         }
102         checksum_len = protocol_version < 21 ? 2 : MD4_SUM_LENGTH;
103 }
104
105 static int show_filelist_p(void)
106 {
107         return verbose && xfer_dirs && !am_server && !inc_recurse;
108 }
109
110 static void start_filelist_progress(char *kind)
111 {
112         rprintf(FCLIENT, "%s ... ", kind);
113         if (verbose > 1 || do_progress)
114                 rprintf(FCLIENT, "\n");
115         rflush(FINFO);
116 }
117
118 static void emit_filelist_progress(int count)
119 {
120         rprintf(FCLIENT, " %d files...\r", count);
121 }
122
123 static void maybe_emit_filelist_progress(int count)
124 {
125         if (do_progress && show_filelist_p() && (count % 100) == 0)
126                 emit_filelist_progress(count);
127 }
128
129 static void finish_filelist_progress(const struct file_list *flist)
130 {
131         if (do_progress) {
132                 /* This overwrites the progress line */
133                 rprintf(FINFO, "%d file%sto consider\n",
134                         flist->count, flist->count == 1 ? " " : "s ");
135         } else
136                 rprintf(FINFO, "done\n");
137 }
138
139 void show_flist_stats(void)
140 {
141         /* Nothing yet */
142 }
143
144 static void list_file_entry(struct file_struct *f)
145 {
146         char permbuf[PERMSTRING_SIZE];
147         double len;
148
149         if (!F_IS_ACTIVE(f)) {
150                 /* this can happen if duplicate names were removed */
151                 return;
152         }
153
154         permstring(permbuf, f->mode);
155         len = F_LENGTH(f);
156
157         /* TODO: indicate '+' if the entry has an ACL. */
158
159 #ifdef SUPPORT_LINKS
160         if (preserve_links && S_ISLNK(f->mode)) {
161                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
162                         permbuf, len, timestring(f->modtime),
163                         f_name(f, NULL), F_SYMLINK(f));
164         } else
165 #endif
166         {
167                 rprintf(FINFO, "%s %11.0f %s %s\n",
168                         permbuf, len, timestring(f->modtime),
169                         f_name(f, NULL));
170         }
171 }
172
173 /* Stat either a symlink or its referent, depending on the settings of
174  * copy_links, copy_unsafe_links, etc.  Returns -1 on error, 0 on success.
175  *
176  * If path is the name of a symlink, then the linkbuf buffer (which must hold
177  * MAXPATHLEN chars) will be set to the symlink's target string.
178  *
179  * The stat structure pointed to by stp will contain information about the
180  * link or the referent as appropriate, if they exist. */
181 static int readlink_stat(const char *path, STRUCT_STAT *stp, char *linkbuf)
182 {
183 #ifdef SUPPORT_LINKS
184         if (link_stat(path, stp, copy_dirlinks) < 0)
185                 return -1;
186         if (S_ISLNK(stp->st_mode)) {
187                 int llen = readlink(path, linkbuf, MAXPATHLEN - 1);
188                 if (llen < 0)
189                         return -1;
190                 linkbuf[llen] = '\0';
191                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
192                         if (verbose > 1) {
193                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
194                                         path, linkbuf);
195                         }
196                         return do_stat(path, stp);
197                 }
198         }
199         return 0;
200 #else
201         return do_stat(path, stp);
202 #endif
203 }
204
205 int link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
206 {
207 #ifdef SUPPORT_LINKS
208         if (copy_links)
209                 return do_stat(path, stp);
210         if (do_lstat(path, stp) < 0)
211                 return -1;
212         if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
213                 STRUCT_STAT st;
214                 if (do_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
215                         *stp = st;
216         }
217         return 0;
218 #else
219         return do_stat(path, stp);
220 #endif
221 }
222
223 /* This function is used to check if a file should be included/excluded
224  * from the list of files based on its name and type etc.  The value of
225  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
226 static int is_excluded(char *fname, int is_dir, int filter_level)
227 {
228 #if 0 /* This currently never happens, so avoid a useless compare. */
229         if (filter_level == NO_FILTERS)
230                 return 0;
231 #endif
232         if (fname) {
233                 /* never exclude '.', even if somebody does --exclude '*' */
234                 if (fname[0] == '.' && !fname[1])
235                         return 0;
236                 /* Handle the -R version of the '.' dir. */
237                 if (fname[0] == '/') {
238                         int len = strlen(fname);
239                         if (fname[len-1] == '.' && fname[len-2] == '/')
240                                 return 0;
241                 }
242         }
243         if (server_filter_list.head
244             && check_filter(&server_filter_list, fname, is_dir) < 0)
245                 return 1;
246         if (filter_level != ALL_FILTERS)
247                 return 0;
248         if (filter_list.head
249             && check_filter(&filter_list, fname, is_dir) < 0)
250                 return 1;
251         return 0;
252 }
253
254 static int to_wire_mode(mode_t mode)
255 {
256 #ifdef SUPPORT_LINKS
257 #if _S_IFLNK != 0120000
258         if (S_ISLNK(mode))
259                 return (mode & ~(_S_IFMT)) | 0120000;
260 #endif
261 #endif
262         return mode;
263 }
264
265 static mode_t from_wire_mode(int mode)
266 {
267 #if _S_IFLNK != 0120000
268         if ((mode & (_S_IFMT)) == 0120000)
269                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
270 #endif
271         return mode;
272 }
273
274 static void send_directory(int f, struct file_list *flist, int ndx,
275                            char *fbuf, int len, int flags);
276
277 static const char *flist_dir, *orig_dir;
278 static int flist_dir_len;
279
280
281 /**
282  * Make sure @p flist is big enough to hold at least @p flist->count
283  * entries.
284  **/
285 void flist_expand(struct file_list *flist)
286 {
287         struct file_struct **new_ptr;
288
289         if (flist->count < flist->malloced)
290                 return;
291
292         if (flist->malloced < FLIST_START)
293                 flist->malloced = FLIST_START;
294         else if (flist->malloced >= FLIST_LINEAR)
295                 flist->malloced += FLIST_LINEAR;
296         else
297                 flist->malloced *= 2;
298
299         /*
300          * In case count jumped or we are starting the list
301          * with a known size just set it.
302          */
303         if (flist->malloced < flist->count)
304                 flist->malloced = flist->count;
305
306         new_ptr = realloc_array(flist->files, struct file_struct *,
307                                 flist->malloced);
308
309         if (verbose >= 2 && flist->malloced != FLIST_START) {
310                 rprintf(FCLIENT, "[%s] expand file_list to %.0f bytes, did%s move\n",
311                     who_am_i(),
312                     (double)sizeof flist->files[0] * flist->malloced,
313                     (new_ptr == flist->files) ? " not" : "");
314         }
315
316         flist->files = new_ptr;
317
318         if (!flist->files)
319                 out_of_memory("flist_expand");
320 }
321
322 int push_flist_dir(const char *dir, int len)
323 {
324         if (dir == flist_dir)
325                 return 1;
326
327         if (!orig_dir)
328                 orig_dir = strdup(curr_dir);
329
330         if (flist_dir && !pop_dir(orig_dir)) {
331                 rsyserr(FERROR, errno, "pop_dir %s failed",
332                         full_fname(orig_dir));
333                 exit_cleanup(RERR_FILESELECT);
334         }
335
336         if (dir && !push_dir(dir, 0)) {
337                 io_error |= IOERR_GENERAL;
338                 rsyserr(FERROR, errno, "push_dir %s failed",
339                         full_fname(dir));
340                 return 0;
341         }
342
343         flist_dir = dir;
344         flist_dir_len = len >= 0 ? len : dir ? (int)strlen(dir) : 0;
345
346         return 1;
347 }
348
349 static void send_file_entry(int f, struct file_struct *file, int ndx)
350 {
351         static time_t modtime;
352         static mode_t mode;
353         static int64 dev;
354         static dev_t rdev;
355         static uint32 rdev_major;
356         static uid_t uid;
357         static gid_t gid;
358         static char *user_name, *group_name;
359         static char lastname[MAXPATHLEN];
360         char fname[MAXPATHLEN];
361         int first_hlink_ndx = -1;
362         int l1, l2;
363         int flags;
364
365         f_name(file, fname);
366
367         flags = file->flags & FLAG_TOP_DIR; /* FLAG_TOP_DIR == XMIT_TOP_DIR */
368
369         if (file->mode == mode)
370                 flags |= XMIT_SAME_MODE;
371         else
372                 mode = file->mode;
373         if ((preserve_devices && IS_DEVICE(mode))
374          || (preserve_specials && IS_SPECIAL(mode))) {
375                 if (protocol_version < 28) {
376                         if (tmp_rdev == rdev)
377                                 flags |= XMIT_SAME_RDEV_pre28;
378                         else
379                                 rdev = tmp_rdev;
380                 } else {
381                         rdev = tmp_rdev;
382                         if ((uint32)major(rdev) == rdev_major)
383                                 flags |= XMIT_SAME_RDEV_MAJOR;
384                         else
385                                 rdev_major = major(rdev);
386                         if ((uint32)minor(rdev) <= 0xFFu)
387                                 flags |= XMIT_RDEV_MINOR_IS_SMALL;
388                 }
389         } else if (protocol_version < 28)
390                 rdev = MAKEDEV(0, 0);
391         if (preserve_uid) {
392                 if (F_UID(file) == uid && *lastname)
393                         flags |= XMIT_SAME_UID;
394                 else {
395                         uid = F_UID(file);
396                         if (preserve_uid && !numeric_ids) {
397                                 user_name = add_uid(uid);
398                                 if (inc_recurse && user_name)
399                                         flags |= XMIT_USER_NAME_FOLLOWS;
400                         }
401                 }
402         }
403         if (preserve_gid) {
404                 if (F_GID(file) == gid && *lastname)
405                         flags |= XMIT_SAME_GID;
406                 else {
407                         gid = F_GID(file);
408                         if (preserve_gid && !numeric_ids) {
409                                 group_name = add_gid(gid);
410                                 if (inc_recurse && group_name)
411                                         flags |= XMIT_GROUP_NAME_FOLLOWS;
412                         }
413                 }
414         }
415         if (file->modtime == modtime)
416                 flags |= XMIT_SAME_TIME;
417         else
418                 modtime = file->modtime;
419
420 #ifdef SUPPORT_HARD_LINKS
421         if (tmp_dev != 0) {
422                 if (protocol_version >= 30) {
423                         struct idev_node *np = idev_node(tmp_dev, tmp_ino);
424                         first_hlink_ndx = (int32)(long)np->data - 1;
425                         if (first_hlink_ndx < 0) {
426                                 np->data = (void*)(long)(ndx + 1);
427                                 flags |= XMIT_HLINK_FIRST;
428                         }
429                         flags |= XMIT_HLINKED;
430                 } else {
431                         if (tmp_dev == dev) {
432                                 if (protocol_version >= 28)
433                                         flags |= XMIT_SAME_DEV_pre30;
434                         } else
435                                 dev = tmp_dev;
436                         flags |= XMIT_HLINKED;
437                 }
438         }
439 #endif
440
441         for (l1 = 0;
442             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
443             l1++) {}
444         l2 = strlen(fname+l1);
445
446         if (l1 > 0)
447                 flags |= XMIT_SAME_NAME;
448         if (l2 > 255)
449                 flags |= XMIT_LONG_NAME;
450
451         /* We must make sure we don't send a zero flag byte or the
452          * other end will terminate the flist transfer.  Note that
453          * the use of XMIT_TOP_DIR on a non-dir has no meaning, so
454          * it's harmless way to add a bit to the first flag byte. */
455         if (protocol_version >= 28) {
456                 if (!flags && !S_ISDIR(mode))
457                         flags |= XMIT_TOP_DIR;
458                 if ((flags & 0xFF00) || !flags) {
459                         flags |= XMIT_EXTENDED_FLAGS;
460                         write_shortint(f, flags);
461                 } else
462                         write_byte(f, flags);
463         } else {
464                 if (!(flags & 0xFF))
465                         flags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
466                 write_byte(f, flags);
467         }
468         if (flags & XMIT_SAME_NAME)
469                 write_byte(f, l1);
470         if (flags & XMIT_LONG_NAME)
471                 write_abbrevint30(f, l2);
472         else
473                 write_byte(f, l2);
474         write_buf(f, fname + l1, l2);
475
476         if (first_hlink_ndx >= 0) {
477                 write_abbrevint30(f, first_hlink_ndx);
478                 goto the_end;
479         }
480
481         write_longint(f, F_LENGTH(file));
482         if (!(flags & XMIT_SAME_TIME))
483                 write_int(f, modtime);
484         if (!(flags & XMIT_SAME_MODE))
485                 write_int(f, to_wire_mode(mode));
486         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
487                 write_abbrevint30(f, uid);
488                 if (flags & XMIT_USER_NAME_FOLLOWS) {
489                         int len = strlen(user_name);
490                         write_byte(f, len);
491                         write_buf(f, user_name, len);
492                 }
493         }
494         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
495                 write_abbrevint30(f, gid);
496                 if (flags & XMIT_GROUP_NAME_FOLLOWS) {
497                         int len = strlen(group_name);
498                         write_byte(f, len);
499                         write_buf(f, group_name, len);
500                 }
501         }
502         if ((preserve_devices && IS_DEVICE(mode))
503          || (preserve_specials && IS_SPECIAL(mode))) {
504                 if (protocol_version < 28) {
505                         if (!(flags & XMIT_SAME_RDEV_pre28))
506                                 write_int(f, (int)rdev);
507                 } else {
508                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
509                                 write_int(f, major(rdev));
510                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
511                                 write_byte(f, minor(rdev));
512                         else
513                                 write_int(f, minor(rdev));
514                 }
515         }
516
517 #ifdef SUPPORT_LINKS
518         if (preserve_links && S_ISLNK(mode)) {
519                 const char *sl = F_SYMLINK(file);
520                 int len = strlen(sl);
521                 write_abbrevint30(f, len);
522                 write_buf(f, sl, len);
523         }
524 #endif
525
526 #ifdef SUPPORT_HARD_LINKS
527         if (tmp_dev != 0 && protocol_version < 30) {
528                 if (protocol_version < 26) {
529                         /* 32-bit dev_t and ino_t */
530                         write_int(f, (int32)dev);
531                         write_int(f, (int32)tmp_ino);
532                 } else {
533                         /* 64-bit dev_t and ino_t */
534                         if (!(flags & XMIT_SAME_DEV_pre30))
535                                 write_longint(f, dev);
536                         write_longint(f, tmp_ino);
537                 }
538         }
539 #endif
540
541         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
542                 const char *sum;
543                 if (S_ISREG(mode))
544                         sum = tmp_sum;
545                 else {
546                         /* Prior to 28, we sent a useless set of nulls. */
547                         sum = empty_sum;
548                 }
549                 write_buf(f, sum, checksum_len);
550         }
551
552   the_end:
553         strlcpy(lastname, fname, MAXPATHLEN);
554
555         if (S_ISREG(mode) || S_ISLNK(mode))
556                 stats.total_size += F_LENGTH(file);
557 }
558
559 static struct file_struct *recv_file_entry(struct file_list *flist,
560                                            int flags, int f)
561 {
562         static time_t modtime;
563         static mode_t mode;
564         static int64 dev;
565         static dev_t rdev;
566         static uint32 rdev_major;
567         static uid_t uid;
568         static gid_t gid;
569         static char lastname[MAXPATHLEN], *lastdir;
570         static int lastdir_depth, lastdir_len = -1;
571         static unsigned int del_hier_name_len = 0;
572         static int in_del_hier = 0;
573         char thisname[MAXPATHLEN];
574         unsigned int l1 = 0, l2 = 0;
575         int alloc_len, basename_len, linkname_len;
576         int extra_len = file_extra_cnt * EXTRA_LEN;
577         int first_hlink_ndx = -1;
578         OFF_T file_length;
579         const char *basename;
580         char *bp;
581         struct file_struct *file;
582
583         if (flags & XMIT_SAME_NAME)
584                 l1 = read_byte(f);
585
586         if (flags & XMIT_LONG_NAME)
587                 l2 = read_abbrevint30(f);
588         else
589                 l2 = read_byte(f);
590
591         if (l2 >= MAXPATHLEN - l1) {
592                 rprintf(FERROR,
593                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s [%s]\n",
594                         flags, l1, l2, lastname, who_am_i());
595                 overflow_exit("recv_file_entry");
596         }
597
598         strlcpy(thisname, lastname, l1 + 1);
599         read_sbuf(f, &thisname[l1], l2);
600         thisname[l1 + l2] = 0;
601
602         strlcpy(lastname, thisname, MAXPATHLEN);
603
604         clean_fname(thisname, 0);
605
606         if (sanitize_paths)
607                 sanitize_path(thisname, thisname, "", 0, NULL);
608
609         if ((basename = strrchr(thisname, '/')) != NULL) {
610                 int len = basename++ - thisname;
611                 if (len != lastdir_len || memcmp(thisname, lastdir, len) != 0) {
612                         lastdir = new_array(char, len + 1);
613                         memcpy(lastdir, thisname, len);
614                         lastdir[len] = '\0';
615                         lastdir_len = len;
616                         lastdir_depth = count_dir_elements(lastdir);
617                 }
618         } else
619                 basename = thisname;
620         basename_len = strlen(basename) + 1; /* count the '\0' */
621
622 #ifdef SUPPORT_HARD_LINKS
623         if (protocol_version >= 30
624          && BITS_SETnUNSET(flags, XMIT_HLINKED, XMIT_HLINK_FIRST)) {
625                 struct file_struct *first;
626                 first_hlink_ndx = read_abbrevint30(f);
627                 if (first_hlink_ndx < 0 || first_hlink_ndx >= flist->count) {
628                         rprintf(FERROR,
629                                 "hard-link reference out of range: %d (%d)\n",
630                                 first_hlink_ndx, flist->count);
631                         exit_cleanup(RERR_PROTOCOL);
632                 }
633                 first = flist->files[first_hlink_ndx];
634                 file_length = F_LENGTH(first);
635                 modtime = first->modtime;
636                 mode = first->mode;
637                 if (preserve_uid)
638                         uid = F_UID(first);
639                 if (preserve_gid)
640                         gid = F_GID(first);
641                 if ((preserve_devices && IS_DEVICE(mode))
642                  || (preserve_specials && IS_SPECIAL(mode))) {
643                         uint32 *devp = F_RDEV_P(first);
644                         rdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
645                 }
646                 if (preserve_links && S_ISLNK(mode))
647                         linkname_len = strlen(F_SYMLINK(first)) + 1;
648                 else
649                         linkname_len = 0;
650                 goto create_object;
651         }
652 #endif
653
654         file_length = read_longint(f);
655         if (!(flags & XMIT_SAME_TIME))
656                 modtime = (time_t)read_int(f);
657         if (!(flags & XMIT_SAME_MODE))
658                 mode = from_wire_mode(read_int(f));
659
660         if (chmod_modes && !S_ISLNK(mode))
661                 mode = tweak_mode(mode, chmod_modes);
662
663         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
664                 uid = (uid_t)read_abbrevint30(f);
665                 if (flags & XMIT_USER_NAME_FOLLOWS)
666                         uid = recv_user_name(f, uid);
667                 else if (inc_recurse && am_root && !numeric_ids)
668                         uid = match_uid(uid);
669         }
670         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
671                 gid = (gid_t)read_abbrevint30(f);
672                 if (flags & XMIT_GROUP_NAME_FOLLOWS)
673                         gid = recv_group_name(f, gid);
674                 else if (inc_recurse && (!am_root || !numeric_ids))
675                         gid = match_gid(gid);
676         }
677
678         if ((preserve_devices && IS_DEVICE(mode))
679          || (preserve_specials && IS_SPECIAL(mode))) {
680                 if (protocol_version < 28) {
681                         if (!(flags & XMIT_SAME_RDEV_pre28))
682                                 rdev = (dev_t)read_int(f);
683                 } else {
684                         uint32 rdev_minor;
685                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
686                                 rdev_major = read_int(f);
687                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
688                                 rdev_minor = read_byte(f);
689                         else
690                                 rdev_minor = read_int(f);
691                         rdev = MAKEDEV(rdev_major, rdev_minor);
692                 }
693                 extra_len += 2 * EXTRA_LEN;
694                 file_length = 0;
695         } else if (protocol_version < 28)
696                 rdev = MAKEDEV(0, 0);
697
698 #ifdef SUPPORT_LINKS
699         if (preserve_links && S_ISLNK(mode)) {
700                 linkname_len = read_abbrevint30(f) + 1; /* count the '\0' */
701                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
702                         rprintf(FERROR, "overflow: linkname_len=%d\n",
703                                 linkname_len - 1);
704                         overflow_exit("recv_file_entry");
705                 }
706         }
707         else
708 #endif
709                 linkname_len = 0;
710
711 #ifdef SUPPORT_HARD_LINKS
712   create_object:
713         if (preserve_hard_links) {
714                 if (protocol_version < 28 && S_ISREG(mode))
715                         flags |= XMIT_HLINKED;
716                 if (flags & XMIT_HLINKED)
717                         extra_len += EXTRA_LEN;
718         }
719 #endif
720
721 #ifdef SUPPORT_ACLS
722         /* We need one or two index int32s when we're preserving ACLs. */
723         if (preserve_acls)
724                 extra_len += (S_ISDIR(mode) ? 2 : 1) * EXTRA_LEN;
725 #endif
726
727         if (always_checksum && S_ISREG(mode))
728                 extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
729
730         if (file_length > 0xFFFFFFFFu && S_ISREG(mode))
731                 extra_len += EXTRA_LEN;
732
733 #if EXTRA_ROUNDING > 0
734         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
735                 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
736 #endif
737
738         if (inc_recurse && S_ISDIR(mode)) {
739                 if (one_file_system) {
740                         /* Room to save the dir's device for -x */
741                         extra_len += 2 * EXTRA_LEN;
742                 }
743                 flist = dir_flist;
744         }
745
746         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
747                   + linkname_len;
748         bp = pool_alloc(flist->file_pool, alloc_len, "recv_file_entry");
749
750         memset(bp, 0, extra_len + FILE_STRUCT_LEN);
751         bp += extra_len;
752         file = (struct file_struct *)bp;
753         bp += FILE_STRUCT_LEN;
754
755         memcpy(bp, basename, basename_len);
756         bp += basename_len + linkname_len; /* skip space for symlink too */
757
758 #ifdef SUPPORT_HARD_LINKS
759         if (flags & XMIT_HLINKED)
760                 file->flags |= FLAG_HLINKED;
761 #endif
762         file->modtime = modtime;
763         file->len32 = (uint32)file_length;
764         if (file_length > 0xFFFFFFFFu && S_ISREG(mode)) {
765                 file->flags |= FLAG_LENGTH64;
766                 OPT_EXTRA(file, 0)->unum = (uint32)(file_length >> 32);
767         }
768         file->mode = mode;
769         if (preserve_uid)
770                 F_OWNER(file) = uid;
771         if (preserve_gid)
772                 F_GROUP(file) = gid;
773
774         if (basename != thisname) {
775                 file->dirname = lastdir;
776                 F_DEPTH(file) = lastdir_depth + 1;
777         } else
778                 F_DEPTH(file) = 1;
779
780         if (S_ISDIR(mode)) {
781                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
782                         F_DEPTH(file)--;
783                 if (flags & XMIT_TOP_DIR) {
784                         in_del_hier = recurse;
785                         del_hier_name_len = F_DEPTH(file) == 0 ? 0 : l1 + l2;
786                         if (relative_paths && del_hier_name_len > 2
787                             && lastname[del_hier_name_len-1] == '.'
788                             && lastname[del_hier_name_len-2] == '/')
789                                 del_hier_name_len -= 2;
790                         file->flags |= FLAG_TOP_DIR | FLAG_XFER_DIR;
791                 } else if (in_del_hier) {
792                         if (!relative_paths || !del_hier_name_len
793                          || (l1 >= del_hier_name_len
794                           && lastname[del_hier_name_len] == '/'))
795                                 file->flags |= FLAG_XFER_DIR;
796                         else
797                                 in_del_hier = 0;
798                 }
799         }
800
801         if ((preserve_devices && IS_DEVICE(mode))
802          || (preserve_specials && IS_SPECIAL(mode))) {
803                 uint32 *devp = F_RDEV_P(file);
804                 DEV_MAJOR(devp) = major(rdev);
805                 DEV_MINOR(devp) = minor(rdev);
806         }
807
808 #ifdef SUPPORT_LINKS
809         if (linkname_len) {
810                 bp = (char*)file->basename + basename_len;
811                 if (first_hlink_ndx >= 0) {
812                         struct file_struct *first = flist->files[first_hlink_ndx];
813                         memcpy(bp, F_SYMLINK(first), linkname_len);
814                 } else
815                         read_sbuf(f, bp, linkname_len - 1);
816                 if (sanitize_paths)
817                         sanitize_path(bp, bp, "", lastdir_depth, NULL);
818         }
819 #endif
820
821 #ifdef SUPPORT_HARD_LINKS
822         if (preserve_hard_links && flags & XMIT_HLINKED) {
823                 if (protocol_version >= 30) {
824                         F_HL_GNUM(file) = flags & XMIT_HLINK_FIRST
825                                         ? flist->count : first_hlink_ndx;
826                 } else {
827                         static int32 cnt = 0;
828                         struct idev_node *np;
829                         int64 ino;
830                         int32 ndx;
831                         if (protocol_version < 26) {
832                                 dev = read_int(f);
833                                 ino = read_int(f);
834                         } else {
835                                 if (!(flags & XMIT_SAME_DEV_pre30))
836                                         dev = read_longint(f);
837                                 ino = read_longint(f);
838                         }
839                         np = idev_node(dev, ino);
840                         ndx = (int32)(long)np->data - 1;
841                         if (ndx < 0) {
842                                 ndx = cnt++;
843                                 np->data = (void*)(long)cnt;
844                         }
845                         F_HL_GNUM(file) = ndx;
846                 }
847         }
848 #endif
849
850         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
851                 if (S_ISREG(mode))
852                         bp = (char*)F_SUM(file);
853                 else {
854                         /* Prior to 28, we get a useless set of nulls. */
855                         bp = tmp_sum;
856                 }
857                 if (first_hlink_ndx >= 0) {
858                         struct file_struct *first = flist->files[first_hlink_ndx];
859                         memcpy(bp, F_SUM(first), checksum_len);
860                 } else
861                         read_buf(f, bp, checksum_len);
862         }
863
864 #ifdef SUPPORT_ACLS
865         if (preserve_acls && !S_ISLNK(mode))
866                 receive_acl(file, f);
867 #endif
868
869         if (S_ISREG(mode) || S_ISLNK(mode))
870                 stats.total_size += file_length;
871
872         return file;
873 }
874
875 /**
876  * Create a file_struct for a named file by reading its stat()
877  * information and performing extensive checks against global
878  * options.
879  *
880  * @return the new file, or NULL if there was an error or this file
881  * should be excluded.
882  *
883  * @todo There is a small optimization opportunity here to avoid
884  * stat()ing the file in some circumstances, which has a certain cost.
885  * We are called immediately after doing readdir(), and so we may
886  * already know the d_type of the file.  We could for example avoid
887  * statting directories if we're not recursing, but this is not a very
888  * important case.  Some systems may not have d_type.
889  **/
890 struct file_struct *make_file(const char *fname, struct file_list *flist,
891                               STRUCT_STAT *stp, int flags, int filter_level)
892 {
893         static char *lastdir;
894         static int lastdir_len = -1;
895         struct file_struct *file;
896         STRUCT_STAT st;
897         char thisname[MAXPATHLEN];
898         char linkname[MAXPATHLEN];
899         int alloc_len, basename_len, linkname_len;
900         int extra_len = file_extra_cnt * EXTRA_LEN;
901         const char *basename;
902         char *bp;
903
904         if (strlcpy(thisname, fname, sizeof thisname)
905             >= sizeof thisname - flist_dir_len) {
906                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
907                 return NULL;
908         }
909         clean_fname(thisname, 0);
910         if (sanitize_paths)
911                 sanitize_path(thisname, thisname, "", 0, NULL);
912
913         if (stp && S_ISDIR(stp->st_mode)) {
914                 st = *stp; /* Needed for "symlink/." with --relative. */
915                 *linkname = '\0'; /* make IBM code checker happy */
916         } else if (readlink_stat(thisname, &st, linkname) != 0) {
917                 int save_errno = errno;
918                 /* See if file is excluded before reporting an error. */
919                 if (filter_level != NO_FILTERS
920                  && (is_excluded(thisname, 0, filter_level)
921                   || is_excluded(thisname, 1, filter_level))) {
922                         if (ignore_perishable && save_errno != ENOENT)
923                                 non_perishable_cnt++;
924                         return NULL;
925                 }
926                 if (save_errno == ENOENT) {
927 #ifdef SUPPORT_LINKS
928                         /* Avoid "vanished" error if symlink points nowhere. */
929                         if (copy_links && do_lstat(thisname, &st) == 0
930                             && S_ISLNK(st.st_mode)) {
931                                 io_error |= IOERR_GENERAL;
932                                 rprintf(FERROR, "symlink has no referent: %s\n",
933                                         full_fname(thisname));
934                         } else
935 #endif
936                         {
937                                 enum logcode c = am_daemon && protocol_version < 28
938                                     ? FERROR : FINFO;
939                                 io_error |= IOERR_VANISHED;
940                                 rprintf(c, "file has vanished: %s\n",
941                                         full_fname(thisname));
942                         }
943                 } else {
944                         io_error |= IOERR_GENERAL;
945                         rsyserr(FERROR, save_errno, "readlink %s failed",
946                                 full_fname(thisname));
947                 }
948                 return NULL;
949         }
950
951         /* backup.c calls us with filter_level set to NO_FILTERS. */
952         if (filter_level == NO_FILTERS)
953                 goto skip_filters;
954
955         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
956                 rprintf(FINFO, "skipping directory %s\n", thisname);
957                 return NULL;
958         }
959
960         /* -x only affects directories because we need to avoid recursing
961          * into a mount-point directory, not to avoid copying a symlinked
962          * file if -L (or similar) was specified. */
963         if (one_file_system && st.st_dev != filesystem_dev
964          && S_ISDIR(st.st_mode)) {
965                 if (one_file_system > 1) {
966                         if (verbose > 2) {
967                                 rprintf(FINFO, "skipping mount-point dir %s\n",
968                                         thisname);
969                         }
970                         return NULL;
971                 }
972                 flags |= FLAG_MOUNT_DIR;
973         }
974
975         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level)) {
976                 if (ignore_perishable)
977                         non_perishable_cnt++;
978                 return NULL;
979         }
980
981         if (lp_ignore_nonreadable(module_id)) {
982 #ifdef SUPPORT_LINKS
983                 if (!S_ISLNK(st.st_mode))
984 #endif
985                         if (access(thisname, R_OK) != 0)
986                                 return NULL;
987         }
988
989   skip_filters:
990
991         /* Only divert a directory in the main transfer. */
992         if (flist && flist->prev && S_ISDIR(st.st_mode)
993          && flags & FLAG_DIVERT_DIRS) {
994                 flist = dir_flist;
995                 /* Room for parent/sibling/next-child info. */
996                 extra_len += 3 * EXTRA_LEN;
997         }
998
999         if (verbose > 2) {
1000                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
1001                         who_am_i(), thisname, filter_level);
1002         }
1003
1004         if ((basename = strrchr(thisname, '/')) != NULL) {
1005                 int len = basename++ - thisname;
1006                 if (len != lastdir_len || memcmp(thisname, lastdir, len) != 0) {
1007                         lastdir = new_array(char, len + 1);
1008                         memcpy(lastdir, thisname, len);
1009                         lastdir[len] = '\0';
1010                         lastdir_len = len;
1011                 }
1012         } else
1013                 basename = thisname;
1014         basename_len = strlen(basename) + 1; /* count the '\0' */
1015
1016 #ifdef SUPPORT_LINKS
1017         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
1018 #else
1019         linkname_len = 0;
1020 #endif
1021
1022         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode))
1023                 extra_len += EXTRA_LEN;
1024
1025 #if EXTRA_ROUNDING > 0
1026         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
1027                 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
1028 #endif
1029
1030         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
1031                   + linkname_len;
1032         if (flist)
1033                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
1034         else {
1035                 if (!(bp = new_array(char, alloc_len)))
1036                         out_of_memory("make_file");
1037         }
1038
1039         memset(bp, 0, extra_len + FILE_STRUCT_LEN);
1040         bp += extra_len;
1041         file = (struct file_struct *)bp;
1042         bp += FILE_STRUCT_LEN;
1043
1044         memcpy(bp, basename, basename_len);
1045         bp += basename_len + linkname_len; /* skip space for symlink too */
1046
1047 #ifdef SUPPORT_HARD_LINKS
1048         if (preserve_hard_links && flist && flist->prev) {
1049                 if (protocol_version >= 28
1050                  ? (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
1051                  : S_ISREG(st.st_mode)) {
1052                         tmp_dev = st.st_dev;
1053                         tmp_ino = st.st_ino;
1054                 } else
1055                         tmp_dev = 0;
1056         }
1057 #endif
1058
1059 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1060         if (IS_DEVICE(st.st_mode) || IS_SPECIAL(st.st_mode)) {
1061                 tmp_rdev = st.st_rdev;
1062                 st.st_size = 0;
1063         }
1064 #endif
1065
1066         file->flags = flags;
1067         file->modtime = st.st_mtime;
1068         file->len32 = (uint32)st.st_size;
1069         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode)) {
1070                 file->flags |= FLAG_LENGTH64;
1071                 OPT_EXTRA(file, 0)->unum = (uint32)(st.st_size >> 32);
1072         }
1073         file->mode = st.st_mode;
1074         if (preserve_uid)
1075                 F_OWNER(file) = st.st_uid;
1076         if (preserve_gid)
1077                 F_GROUP(file) = st.st_gid;
1078
1079         if (basename != thisname)
1080                 file->dirname = lastdir;
1081
1082 #ifdef SUPPORT_LINKS
1083         if (linkname_len) {
1084                 bp = (char*)file->basename + basename_len;
1085                 memcpy(bp, linkname, linkname_len);
1086         }
1087 #endif
1088
1089         if (always_checksum && am_sender && S_ISREG(st.st_mode))
1090                 file_checksum(thisname, tmp_sum, st.st_size);
1091
1092         F_ROOTDIR(file) = flist_dir;
1093
1094         /* This code is only used by the receiver when it is building
1095          * a list of files for a delete pass. */
1096         if (keep_dirlinks && linkname_len && flist) {
1097                 STRUCT_STAT st2;
1098                 int save_mode = file->mode;
1099                 file->mode = S_IFDIR; /* Find a directory with our name. */
1100                 if (flist_find(dir_flist, file) >= 0
1101                     && do_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
1102                         file->modtime = st2.st_mtime;
1103                         file->len32 = 0;
1104                         file->mode = st2.st_mode;
1105                         if (preserve_uid)
1106                                 F_OWNER(file) = st2.st_uid;
1107                         if (preserve_gid)
1108                                 F_GROUP(file) = st2.st_gid;
1109                 } else
1110                         file->mode = save_mode;
1111         }
1112
1113         if (basename_len == 0+1)
1114                 return NULL;
1115
1116         if (inc_recurse && flist == dir_flist) {
1117                 flist_expand(flist);
1118                 flist->files[flist->count++] = file;
1119         }
1120
1121         return file;
1122 }
1123
1124 /* Only called for temporary file_struct entries created by make_file(). */
1125 void unmake_file(struct file_struct *file)
1126 {
1127         int extra_cnt = file_extra_cnt + LEN64_BUMP(file);
1128 #if EXTRA_ROUNDING > 0
1129         if (extra_cnt & EXTRA_ROUNDING)
1130                 extra_cnt = (extra_cnt | EXTRA_ROUNDING) + 1;
1131 #endif
1132         free(REQ_EXTRA(file, extra_cnt));
1133 }
1134
1135 static struct file_struct *send_file_name(int f, struct file_list *flist,
1136                                           char *fname, STRUCT_STAT *stp,
1137                                           int flags, int filter_flags)
1138 {
1139         struct file_struct *file;
1140 #ifdef SUPPORT_ACLS
1141         statx sx;
1142 #endif
1143
1144         file = make_file(fname, flist, stp, flags, filter_flags);
1145         if (!file)
1146                 return NULL;
1147
1148         if (chmod_modes && !S_ISLNK(file->mode))
1149                 file->mode = tweak_mode(file->mode, chmod_modes);
1150
1151 #ifdef SUPPORT_ACLS
1152         if (preserve_acls && !S_ISLNK(file->mode) && f >= 0) {
1153                 sx.st.st_mode = file->mode;
1154                 sx.acc_acl = sx.def_acl = NULL;
1155                 if (get_acl(fname, &sx) < 0)
1156                         return NULL;
1157         }
1158 #endif
1159
1160         maybe_emit_filelist_progress(flist->count + flist_count_offset);
1161
1162         flist_expand(flist);
1163         flist->files[flist->count++] = file;
1164         if (f >= 0) {
1165                 send_file_entry(f, file, flist->count - 1);
1166 #ifdef SUPPORT_ACLS
1167                 if (preserve_acls && !S_ISLNK(file->mode)) {
1168                         send_acl(&sx, f);
1169                         free_acl(&sx);
1170                 }
1171 #endif
1172         }
1173         return file;
1174 }
1175
1176 static void send_if_directory(int f, struct file_list *flist,
1177                               struct file_struct *file,
1178                               char *fbuf, unsigned int ol,
1179                               int flags)
1180 {
1181         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
1182
1183         if (S_ISDIR(file->mode)
1184             && !(file->flags & FLAG_MOUNT_DIR) && f_name(file, fbuf)) {
1185                 void *save_filters;
1186                 unsigned int len = strlen(fbuf);
1187                 if (len > 1 && fbuf[len-1] == '/')
1188                         fbuf[--len] = '\0';
1189                 if (len >= MAXPATHLEN - 1) {
1190                         io_error |= IOERR_GENERAL;
1191                         rprintf(FERROR, "skipping long-named directory: %s\n",
1192                                 full_fname(fbuf));
1193                         return;
1194                 }
1195                 save_filters = push_local_filters(fbuf, len);
1196                 send_directory(f, flist, -1, fbuf, len, flags);
1197                 pop_local_filters(save_filters);
1198                 fbuf[ol] = '\0';
1199                 if (is_dot_dir)
1200                         fbuf[ol-1] = '.';
1201         }
1202 }
1203
1204 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1205 {
1206         return f_name_cmp(*file1, *file2);
1207 }
1208
1209 /* We take an entire set of sibling dirs from dir_flist (start <= ndx <= end),
1210  * sort them by name, and link them into the tree, setting the appropriate
1211  * parent/child/sibling pointers. */
1212 static void add_dirs_to_tree(int parent_ndx, int start, int end)
1213 {
1214         int i;
1215         int32 *dp = NULL;
1216         int32 *parent_dp = parent_ndx < 0 ? NULL
1217                          : F_DIRNODE_P(dir_flist->files[parent_ndx]);
1218
1219         qsort(dir_flist->files + start, end - start + 1,
1220               sizeof dir_flist->files[0], (int (*)())file_compare);
1221
1222         for (i = start; i <= end; i++) {
1223                 struct file_struct *file = dir_flist->files[i];
1224                 if (!(file->flags & FLAG_XFER_DIR)
1225                  || file->flags & FLAG_MOUNT_DIR)
1226                         continue;
1227                 if (dp)
1228                         DIR_NEXT_SIBLING(dp) = i;
1229                 else if (parent_dp)
1230                         DIR_FIRST_CHILD(parent_dp) = i;
1231                 else
1232                         send_dir_ndx = i;
1233                 dp = F_DIRNODE_P(file);
1234                 DIR_PARENT(dp) = parent_ndx;
1235                 DIR_FIRST_CHILD(dp) = -1;
1236         }
1237         if (dp)
1238                 DIR_NEXT_SIBLING(dp) = -1;
1239 }
1240
1241 /* This function is normally called by the sender, but the receiving side also
1242  * calls it from get_dirlist() with f set to -1 so that we just construct the
1243  * file list in memory without sending it over the wire.  Also, get_dirlist()
1244  * might call this with f set to -2, which also indicates that local filter
1245  * rules should be ignored. */
1246 static void send_directory(int f, struct file_list *flist, int parent_ndx,
1247                            char *fbuf, int len, int flags)
1248 {
1249         struct dirent *di;
1250         unsigned remainder;
1251         char *p;
1252         DIR *d;
1253         int divert_dirs = (flags & FLAG_DIVERT_DIRS) != 0;
1254         int start = divert_dirs ? dir_flist->count : flist->count;
1255         int filter_flags = f == -2 ? SERVER_FILTERS : ALL_FILTERS;
1256
1257         assert(flist != NULL);
1258
1259         if (!(d = opendir(fbuf))) {
1260                 io_error |= IOERR_GENERAL;
1261                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1262                 return;
1263         }
1264
1265         p = fbuf + len;
1266         if (len != 1 || *fbuf != '/')
1267                 *p++ = '/';
1268         *p = '\0';
1269         remainder = MAXPATHLEN - (p - fbuf);
1270
1271         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1272                 char *dname = d_name(di);
1273                 if (dname[0] == '.' && (dname[1] == '\0'
1274                     || (dname[1] == '.' && dname[2] == '\0')))
1275                         continue;
1276                 if (strlcpy(p, dname, remainder) >= remainder) {
1277                         io_error |= IOERR_GENERAL;
1278                         rprintf(FINFO,
1279                                 "cannot send long-named file %s\n",
1280                                 full_fname(fbuf));
1281                         continue;
1282                 }
1283
1284                 send_file_name(f, flist, fbuf, NULL, flags, filter_flags);
1285         }
1286
1287         fbuf[len] = '\0';
1288
1289         if (errno) {
1290                 io_error |= IOERR_GENERAL;
1291                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1292         }
1293
1294         closedir(d);
1295
1296         if (f < 0)
1297                 return;
1298
1299         if (divert_dirs)
1300                 add_dirs_to_tree(parent_ndx, start, dir_flist->count - 1);
1301         else if (recurse) {
1302                 int i, end = flist->count - 1;
1303                 /* send_if_directory() bumps flist->count, so use "end". */
1304                 for (i = start; i <= end; i++)
1305                         send_if_directory(f, flist, flist->files[i], fbuf, len, flags);
1306         }
1307 }
1308
1309 void send_extra_file_list(int f, int at_least)
1310 {
1311         char fbuf[MAXPATHLEN];
1312         struct file_list *flist;
1313         int64 start_write;
1314         int future_cnt, save_io_error = io_error;
1315
1316         if (send_dir_ndx < 0)
1317                 return;
1318
1319         /* Keep sending data until we have the requested number of
1320          * files in the upcoming file-lists. */
1321         if (cur_flist->next) {
1322                 flist = first_flist->prev; /* the newest flist */
1323                 future_cnt = flist->count
1324                            + flist->ndx_start - cur_flist->next->ndx_start;
1325         } else
1326                 future_cnt = 0;
1327         while (future_cnt < at_least) {
1328                 struct file_struct *file = dir_flist->files[send_dir_ndx];
1329                 int32 *dp;
1330                 int dlen;
1331
1332                 f_name(file, fbuf);
1333                 dlen = strlen(fbuf);
1334
1335                 if (F_ROOTDIR(file) != flist_dir) {
1336                         if (!push_flist_dir(F_ROOTDIR(file), -1))
1337                                 exit_cleanup(RERR_FILESELECT);
1338                 }
1339
1340                 flist = flist_new(0, "send_extra_file_list");
1341                 start_write = stats.total_written;
1342
1343                 write_ndx(f, NDX_FLIST_OFFSET - send_dir_ndx);
1344                 change_local_filter_dir(fbuf, dlen, send_dir_depth);
1345                 send_directory(f, flist, send_dir_ndx, fbuf, dlen, FLAG_DIVERT_DIRS | FLAG_XFER_DIR);
1346                 write_byte(f, 0);
1347
1348                 clean_flist(flist, 0, 0);
1349                 file_total += flist->count;
1350                 future_cnt += flist->count;
1351                 stats.flist_size += stats.total_written - start_write;
1352                 stats.num_files += flist->count;
1353                 if (verbose > 3)
1354                         output_flist(flist);
1355
1356                 dp = F_DIRNODE_P(file);
1357                 if (DIR_FIRST_CHILD(dp) >= 0) {
1358                         send_dir_ndx = DIR_FIRST_CHILD(dp);
1359                         send_dir_depth++;
1360                 } else {
1361                         while (DIR_NEXT_SIBLING(dp) < 0) {
1362                                 if ((send_dir_ndx = DIR_PARENT(dp)) < 0) {
1363                                         write_ndx(f, NDX_FLIST_EOF);
1364                                         flist_eof = 1;
1365                                         change_local_filter_dir(NULL, 0, 0);
1366                                         goto finish;
1367                                 }
1368                                 send_dir_depth--;
1369                                 file = dir_flist->files[send_dir_ndx];
1370                                 dp = F_DIRNODE_P(file);
1371                         }
1372                         send_dir_ndx = DIR_NEXT_SIBLING(dp);
1373                 }
1374         }
1375
1376   finish:
1377         if (io_error != save_io_error && !ignore_errors)
1378                 send_msg_int(MSG_IO_ERROR, io_error);
1379 }
1380
1381 struct file_list *send_file_list(int f, int argc, char *argv[])
1382 {
1383         int len;
1384         STRUCT_STAT st;
1385         char *p, *dir;
1386         char lastpath[MAXPATHLEN] = "";
1387         struct file_list *flist;
1388         struct timeval start_tv, end_tv;
1389         int64 start_write;
1390         int use_ff_fd = 0;
1391         int flags, disable_buffering;
1392
1393         rprintf(FLOG, "building file list\n");
1394         if (show_filelist_p())
1395                 start_filelist_progress("building file list");
1396         else if (inc_recurse && verbose && !am_server)
1397                 rprintf(FCLIENT, "sending incremental file list\n");
1398
1399         start_write = stats.total_written;
1400         gettimeofday(&start_tv, NULL);
1401
1402 #ifdef SUPPORT_HARD_LINKS
1403         if (preserve_hard_links && protocol_version >= 30 && !cur_flist)
1404                 init_hard_links();
1405 #endif
1406
1407         flist = cur_flist = flist_new(0, "send_file_list");
1408         if (inc_recurse) {
1409                 dir_flist = flist_new(FLIST_TEMP, "send_file_list");
1410                 flags = FLAG_DIVERT_DIRS;
1411         } else {
1412                 dir_flist = cur_flist;
1413                 flags = 0;
1414         }
1415
1416         disable_buffering = io_start_buffering_out(f);
1417         if (filesfrom_fd >= 0) {
1418                 if (argv[0] && !push_dir(argv[0], 0)) {
1419                         rsyserr(FERROR, errno, "push_dir %s failed",
1420                                 full_fname(argv[0]));
1421                         exit_cleanup(RERR_FILESELECT);
1422                 }
1423                 use_ff_fd = 1;
1424         }
1425
1426         while (1) {
1427                 char fbuf[MAXPATHLEN];
1428                 char *fn;
1429                 int is_dot_dir;
1430
1431                 if (use_ff_fd) {
1432                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1433                                 break;
1434                         sanitize_path(fbuf, fbuf, "", 0, NULL);
1435                 } else {
1436                         if (argc-- == 0)
1437                                 break;
1438                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1439                         if (sanitize_paths)
1440                                 sanitize_path(fbuf, fbuf, "", 0, NULL);
1441                 }
1442
1443                 len = strlen(fbuf);
1444                 if (relative_paths) {
1445                         /* We clean up fbuf below. */
1446                         is_dot_dir = 0;
1447                 } else if (!len || fbuf[len - 1] == '/') {
1448                         if (len == 2 && fbuf[0] == '.') {
1449                                 /* Turn "./" into just "." rather than "./." */
1450                                 fbuf[1] = '\0';
1451                         } else {
1452                                 if (len + 1 >= MAXPATHLEN)
1453                                         overflow_exit("send_file_list");
1454                                 fbuf[len++] = '.';
1455                                 fbuf[len] = '\0';
1456                         }
1457                         is_dot_dir = 1;
1458                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1459                     && (len == 2 || fbuf[len-3] == '/')) {
1460                         if (len + 2 >= MAXPATHLEN)
1461                                 overflow_exit("send_file_list");
1462                         fbuf[len++] = '/';
1463                         fbuf[len++] = '.';
1464                         fbuf[len] = '\0';
1465                         is_dot_dir = 1;
1466                 } else {
1467                         is_dot_dir = fbuf[len-1] == '.'
1468                                    && (len == 1 || fbuf[len-2] == '/');
1469                 }
1470
1471                 if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
1472                         io_error |= IOERR_GENERAL;
1473                         rsyserr(FERROR, errno, "link_stat %s failed",
1474                                 full_fname(fbuf));
1475                         continue;
1476                 }
1477
1478                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1479                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1480                         continue;
1481                 }
1482
1483                 dir = NULL;
1484
1485                 if (!relative_paths) {
1486                         p = strrchr(fbuf, '/');
1487                         if (p) {
1488                                 *p = '\0';
1489                                 if (p == fbuf)
1490                                         dir = "/";
1491                                 else
1492                                         dir = fbuf;
1493                                 len -= p - fbuf + 1;
1494                                 fn = p + 1;
1495                         } else
1496                                 fn = fbuf;
1497                 } else {
1498                         if ((p = strstr(fbuf, "/./")) != NULL) {
1499                                 *p = '\0';
1500                                 if (p == fbuf)
1501                                         dir = "/";
1502                                 else
1503                                         dir = fbuf;
1504                                 len -= p - fbuf + 3;
1505                                 fn = p + 3;
1506                         } else
1507                                 fn = fbuf;
1508                         /* Get rid of trailing "/" and "/.". */
1509                         while (len) {
1510                                 if (fn[len - 1] == '/') {
1511                                         is_dot_dir = 1;
1512                                         if (!--len && !dir) {
1513                                                 len++;
1514                                                 break;
1515                                         }
1516                                 }
1517                                 else if (len >= 2 && fn[len - 1] == '.'
1518                                                   && fn[len - 2] == '/') {
1519                                         is_dot_dir = 1;
1520                                         if (!(len -= 2) && !dir) {
1521                                                 len++;
1522                                                 break;
1523                                         }
1524                                 } else
1525                                         break;
1526                         }
1527                         if (len == 1 && fn[0] == '/')
1528                                 fn[len++] = '.';
1529                         fn[len] = '\0';
1530                         /* Reject a ".." dir in the active part of the path. */
1531                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1532                                 if ((p[2] == '/' || p[2] == '\0')
1533                                  && (p == fn || p[-1] == '/')) {
1534                                         rprintf(FERROR,
1535                                             "found \"..\" dir in relative path: %s\n",
1536                                             fbuf);
1537                                         exit_cleanup(RERR_SYNTAX);
1538                                 }
1539                         }
1540                 }
1541
1542                 if (!*fn) {
1543                         len = 1;
1544                         fn = ".";
1545                 }
1546
1547                 if (dir && *dir) {
1548                         static const char *lastdir;
1549                         static int lastdir_len = -1;
1550                         int len = strlen(dir);
1551
1552                         if (len != lastdir_len || memcmp(lastdir, dir, len) != 0) {
1553                                 if (!push_flist_dir(strdup(dir), len))
1554                                         goto push_error;
1555                                 lastdir = flist_dir;
1556                                 lastdir_len = flist_dir_len;
1557                         } else if (!push_flist_dir(lastdir, lastdir_len)) {
1558                           push_error:
1559                                 io_error |= IOERR_GENERAL;
1560                                 rsyserr(FERROR, errno, "push_dir %s failed",
1561                                         full_fname(dir));
1562                                 continue;
1563                         }
1564                 }
1565
1566                 if (fn != fbuf)
1567                         memmove(fbuf, fn, len + 1);
1568
1569                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1570                         /* Send the implied directories at the start of the
1571                          * source spec, so we get their permissions right. */
1572                         char *lp = lastpath, *slash = fbuf;
1573                         *p = '\0';
1574                         /* Skip any initial directories in our path that we
1575                          * have in common with lastpath. */
1576                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1577                                 if (*fn == '/')
1578                                         slash = fn;
1579                         }
1580                         *p = '/';
1581                         if (fn != p || (*lp && *lp != '/')) {
1582                                 int save_copy_links = copy_links;
1583                                 int save_xfer_dirs = xfer_dirs;
1584                                 int dir_flags = inc_recurse ? FLAG_DIVERT_DIRS : 0;
1585                                 copy_links |= copy_unsafe_links;
1586                                 xfer_dirs = 1;
1587                                 while ((slash = strchr(slash+1, '/')) != 0) {
1588                                         *slash = '\0';
1589                                         send_file_name(f, flist, fbuf, NULL,
1590                                                        dir_flags, ALL_FILTERS);
1591                                         *slash = '/';
1592                                 }
1593                                 copy_links = save_copy_links;
1594                                 xfer_dirs = save_xfer_dirs;
1595                                 *p = '\0';
1596                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1597                                 *p = '/';
1598                         }
1599                 }
1600
1601                 if (one_file_system)
1602                         filesystem_dev = st.st_dev;
1603
1604                 if (recurse || (xfer_dirs && is_dot_dir)) {
1605                         struct file_struct *file;
1606                         int top_flags = FLAG_TOP_DIR | FLAG_XFER_DIR
1607                                       | (is_dot_dir ? 0 : flags)
1608                                       | (inc_recurse ? FLAG_DIVERT_DIRS : 0);
1609                         file = send_file_name(f, flist, fbuf, &st,
1610                                               top_flags, ALL_FILTERS);
1611                         if (file && !inc_recurse)
1612                                 send_if_directory(f, flist, file, fbuf, len, flags);
1613                 } else
1614                         send_file_name(f, flist, fbuf, &st, flags, ALL_FILTERS);
1615         }
1616
1617         gettimeofday(&end_tv, NULL);
1618         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1619                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1620         if (stats.flist_buildtime == 0)
1621                 stats.flist_buildtime = 1;
1622         start_tv = end_tv;
1623
1624         write_byte(f, 0); /* Indicate end of file list */
1625
1626 #ifdef SUPPORT_HARD_LINKS
1627         if (preserve_hard_links && protocol_version >= 30 && !inc_recurse)
1628                 idev_destroy();
1629 #endif
1630
1631         if (show_filelist_p())
1632                 finish_filelist_progress(flist);
1633
1634         gettimeofday(&end_tv, NULL);
1635         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1636                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1637
1638         /* Sort the list without removing any duplicates in non-incremental
1639          * mode.  This allows the receiving side to ask for whatever name it
1640          * kept.  For incremental mode, the sender also removes duplicates
1641          * in this initial file-list so that it avoids re-sending duplicated
1642          * directories. */
1643         clean_flist(flist, 0, inc_recurse);
1644         file_total += flist->count;
1645
1646         if (!numeric_ids && !inc_recurse)
1647                 send_uid_list(f);
1648
1649         /* send the io_error flag */
1650         if (protocol_version < 30)
1651                 write_int(f, ignore_errors ? 0 : io_error);
1652         else if (io_error && !ignore_errors)
1653                 send_msg_int(MSG_IO_ERROR, io_error);
1654
1655         if (disable_buffering)
1656                 io_end_buffering_out();
1657
1658         stats.flist_size = stats.total_written - start_write;
1659         stats.num_files = flist->count;
1660
1661         if (verbose > 3)
1662                 output_flist(flist);
1663
1664         if (verbose > 2)
1665                 rprintf(FINFO, "send_file_list done\n");
1666
1667         if (inc_recurse) {
1668                 add_dirs_to_tree(-1, 0, dir_flist->count - 1);
1669                 if (file_total == 1) {
1670                         /* If we're creating incremental file-lists and there
1671                          * was just 1 item in the first file-list, send 1 more
1672                          * file-list to check if this is a 1-file xfer. */
1673                         if (send_dir_ndx < 0)
1674                                 write_ndx(f, NDX_DONE);
1675                         else
1676                                 send_extra_file_list(f, 1);
1677                 }
1678         }
1679
1680         return flist;
1681 }
1682
1683 struct file_list *recv_file_list(int f)
1684 {
1685         struct file_list *flist;
1686         int dstart, flags;
1687         int64 start_read;
1688
1689         if (!first_flist)
1690                 rprintf(FLOG, "receiving file list\n");
1691         if (show_filelist_p())
1692                 start_filelist_progress("receiving file list");
1693         else if (inc_recurse && verbose && !am_server && !first_flist)
1694                 rprintf(FCLIENT, "receiving incremental file list\n");
1695
1696         start_read = stats.total_read;
1697
1698         flist = flist_new(0, "recv_file_list");
1699
1700 #ifdef SUPPORT_HARD_LINKS
1701         if (preserve_hard_links && protocol_version < 30)
1702                 init_hard_links();
1703 #endif
1704
1705         if (inc_recurse) {
1706                 if (flist->ndx_start == 0)
1707                         dir_flist = flist_new(FLIST_TEMP, "recv_file_list");
1708                 dstart = dir_flist->count;
1709         } else {
1710                 dir_flist = flist;
1711                 dstart = 0;
1712         }
1713
1714         while ((flags = read_byte(f)) != 0) {
1715                 struct file_struct *file;
1716
1717                 flist_expand(flist);
1718
1719                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1720                         flags |= read_byte(f) << 8;
1721                 file = recv_file_entry(flist, flags, f);
1722
1723                 if (inc_recurse && S_ISDIR(file->mode)) {
1724                         flist_expand(dir_flist);
1725                         dir_flist->files[dir_flist->count++] = file;
1726                 }
1727
1728                 flist->files[flist->count++] = file;
1729
1730                 maybe_emit_filelist_progress(flist->count);
1731
1732                 if (verbose > 2) {
1733                         rprintf(FINFO, "recv_file_name(%s)\n",
1734                                 f_name(file, NULL));
1735                 }
1736         }
1737         file_total += flist->count;
1738
1739         if (verbose > 2)
1740                 rprintf(FINFO, "received %d names\n", flist->count);
1741
1742         if (show_filelist_p())
1743                 finish_filelist_progress(flist);
1744
1745         clean_flist(flist, relative_paths, 1);
1746
1747         if (inc_recurse) {
1748                 qsort(dir_flist->files + dstart, dir_flist->count - dstart,
1749                       sizeof dir_flist->files[0], (int (*)())file_compare);
1750         } else if (f >= 0)
1751                 recv_uid_list(f, flist);
1752
1753         if (protocol_version < 30) {
1754                 /* Recv the io_error flag */
1755                 if (ignore_errors)
1756                         read_int(f);
1757                 else
1758                         io_error |= read_int(f);
1759         }
1760
1761         if (verbose > 3)
1762                 output_flist(flist);
1763
1764         if (list_only) {
1765                 int i;
1766                 for (i = 0; i < flist->count; i++)
1767                         list_file_entry(flist->files[i]);
1768         }
1769
1770         if (verbose > 2)
1771                 rprintf(FINFO, "recv_file_list done\n");
1772
1773         stats.flist_size += stats.total_read - start_read;
1774         stats.num_files += flist->count;
1775
1776         return flist;
1777 }
1778
1779 /* This is only used once by the receiver if the very first file-list
1780  * has exactly one item in it. */
1781 void recv_additional_file_list(int f)
1782 {
1783         struct file_list *flist;
1784         int ndx = read_ndx(f);
1785         if (ndx == NDX_DONE) {
1786                 flist_eof = 1;
1787                 change_local_filter_dir(NULL, 0, 0);
1788         } else {
1789                 ndx = NDX_FLIST_OFFSET - ndx;
1790                 if (ndx < 0 || ndx >= dir_flist->count) {
1791                         ndx = NDX_FLIST_OFFSET - ndx;
1792                         rprintf(FERROR,
1793                                 "Invalid dir index: %d (%d - %d)\n",
1794                                 ndx, NDX_FLIST_OFFSET,
1795                                 NDX_FLIST_OFFSET - dir_flist->count);
1796                         exit_cleanup(RERR_PROTOCOL);
1797                 }
1798                 flist = recv_file_list(f);
1799                 flist->parent_ndx = ndx;
1800         }
1801 }
1802
1803 /* Search for an identically-named item in the file list.  Note that the
1804  * items must agree in their directory-ness, or no match is returned. */
1805 int flist_find(struct file_list *flist, struct file_struct *f)
1806 {
1807         int low = flist->low, high = flist->high;
1808         int diff, mid, mid_up;
1809
1810         while (low <= high) {
1811                 mid = (low + high) / 2;
1812                 if (F_IS_ACTIVE(flist->files[mid]))
1813                         mid_up = mid;
1814                 else {
1815                         /* Scan for the next non-empty entry using the cached
1816                          * distance values.  If the value isn't fully up-to-
1817                          * date, update it. */
1818                         mid_up = mid + F_DEPTH(flist->files[mid]);
1819                         if (!F_IS_ACTIVE(flist->files[mid_up])) {
1820                                 do {
1821                                     mid_up += F_DEPTH(flist->files[mid_up]);
1822                                 } while (!F_IS_ACTIVE(flist->files[mid_up]));
1823                                 F_DEPTH(flist->files[mid]) = mid_up - mid;
1824                         }
1825                         if (mid_up > high) {
1826                                 /* If there's nothing left above us, set high to
1827                                  * a non-empty entry below us and continue. */
1828                                 high = mid - (int)flist->files[mid]->len32;
1829                                 if (!F_IS_ACTIVE(flist->files[high])) {
1830                                         do {
1831                                             high -= (int)flist->files[high]->len32;
1832                                         } while (!F_IS_ACTIVE(flist->files[high]));
1833                                         flist->files[mid]->len32 = mid - high;
1834                                 }
1835                                 continue;
1836                         }
1837                 }
1838                 diff = f_name_cmp(flist->files[mid_up], f);
1839                 if (diff == 0) {
1840                         if (protocol_version < 29
1841                             && S_ISDIR(flist->files[mid_up]->mode)
1842                             != S_ISDIR(f->mode))
1843                                 return -1;
1844                         return mid_up;
1845                 }
1846                 if (diff < 0)
1847                         low = mid_up + 1;
1848                 else
1849                         high = mid - 1;
1850         }
1851         return -1;
1852 }
1853
1854 /*
1855  * Free up any resources a file_struct has allocated
1856  * and clear the file.
1857  */
1858 void clear_file(struct file_struct *file)
1859 {
1860         /* The +1 zeros out the first char of the basename. */
1861         memset(file, 0, FILE_STRUCT_LEN + 1);
1862         /* In an empty entry, F_DEPTH() is an offset to the next non-empty
1863          * entry.  Likewise for len32 in the opposite direction.  We assume
1864          * that we're alone for now since flist_find() will adjust the counts
1865          * it runs into that aren't up-to-date. */
1866         file->len32 = F_DEPTH(file) = 1;
1867 }
1868
1869 /* Allocate a new file list. */
1870 struct file_list *flist_new(int flags, char *msg)
1871 {
1872         struct file_list *flist;
1873
1874         flist = new(struct file_list);
1875         if (!flist)
1876                 out_of_memory(msg);
1877
1878         memset(flist, 0, sizeof flist[0]);
1879
1880         if (!(flags & FLIST_TEMP)) {
1881                 if (first_flist) {
1882                         flist->ndx_start = first_flist->prev->ndx_start
1883                                          + first_flist->prev->count;
1884                 }
1885                 /* This is a doubly linked list with prev looping back to
1886                  * the end of the list, but the last next pointer is NULL. */
1887                 if (!first_flist)
1888                         first_flist = cur_flist = flist->prev = flist;
1889                 else {
1890                         flist->prev = first_flist->prev;
1891                         flist->prev->next = first_flist->prev = flist;
1892                 }
1893                 flist_cnt++;
1894         }
1895
1896         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0, out_of_memory, POOL_INTERN)))
1897                 out_of_memory(msg);
1898
1899         return flist;
1900 }
1901
1902 /* Free up all elements in a flist. */
1903 void flist_free(struct file_list *flist)
1904 {
1905         if (!flist->prev)
1906                 ; /* Was FLIST_TEMP dir-list. */
1907         else if (flist == flist->prev) {
1908                 first_flist = cur_flist = NULL;
1909                 file_total = 0;
1910                 flist_cnt = 0;
1911         } else {
1912                 if (flist == cur_flist)
1913                         cur_flist = flist->next;
1914                 if (flist == first_flist)
1915                         first_flist = first_flist->next;
1916                 else {
1917                         flist->prev->next = flist->next;
1918                         if (!flist->next)
1919                                 flist->next = first_flist;
1920                 }
1921                 flist->next->prev = flist->prev;
1922                 file_total -= flist->count;
1923                 flist_cnt--;
1924         }
1925
1926         pool_destroy(flist->file_pool);
1927         free(flist->files);
1928         free(flist);
1929 }
1930
1931 /*
1932  * This routine ensures we don't have any duplicate names in our file list.
1933  * duplicate names can cause corruption because of the pipelining
1934  */
1935 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1936 {
1937         char fbuf[MAXPATHLEN];
1938         int i, prev_i = 0;
1939
1940         if (!flist)
1941                 return;
1942         if (flist->count == 0) {
1943                 flist->high = -1;
1944                 return;
1945         }
1946
1947         qsort(flist->files, flist->count,
1948             sizeof flist->files[0], (int (*)())file_compare);
1949
1950         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1951                 if (F_IS_ACTIVE(flist->files[i])) {
1952                         prev_i = i;
1953                         break;
1954                 }
1955         }
1956         flist->low = prev_i;
1957         while (++i < flist->count) {
1958                 int j;
1959                 struct file_struct *file = flist->files[i];
1960
1961                 if (!F_IS_ACTIVE(file))
1962                         continue;
1963                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1964                         j = prev_i;
1965                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1966                         int save_mode = file->mode;
1967                         /* Make sure that this directory doesn't duplicate a
1968                          * non-directory earlier in the list. */
1969                         flist->high = prev_i;
1970                         file->mode = S_IFREG;
1971                         j = flist_find(flist, file);
1972                         file->mode = save_mode;
1973                 } else
1974                         j = -1;
1975                 if (j >= 0) {
1976                         struct file_struct *fp = flist->files[j];
1977                         int keep, drop;
1978                         /* If one is a dir and the other is not, we want to
1979                          * keep the dir because it might have contents in the
1980                          * list. */
1981                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1982                                 if (S_ISDIR(file->mode))
1983                                         keep = i, drop = j;
1984                                 else
1985                                         keep = j, drop = i;
1986                         } else if (protocol_version < 27)
1987                                 keep = j, drop = i;
1988                         else
1989                                 keep = i, drop = j;
1990                         if (verbose > 1 && !am_server) {
1991                                 rprintf(FINFO,
1992                                         "removing duplicate name %s from file list (%d)\n",
1993                                         f_name(file, fbuf), drop);
1994                         }
1995                         /* Make sure we don't lose track of a user-specified
1996                          * top directory. */
1997                         flist->files[keep]->flags |= flist->files[drop]->flags
1998                                                    & (FLAG_TOP_DIR|FLAG_XFER_DIR);
1999
2000                         clear_file(flist->files[drop]);
2001
2002                         if (keep == i) {
2003                                 if (flist->low == drop) {
2004                                         for (j = drop + 1;
2005                                              j < i && !F_IS_ACTIVE(flist->files[j]);
2006                                              j++) {}
2007                                         flist->low = j;
2008                                 }
2009                                 prev_i = i;
2010                         }
2011                 } else
2012                         prev_i = i;
2013         }
2014         flist->high = no_dups ? prev_i : flist->count - 1;
2015
2016         if (strip_root) {
2017                 /* We need to strip off the leading slashes for relative
2018                  * paths, but this must be done _after_ the sorting phase. */
2019                 for (i = flist->low; i <= flist->high; i++) {
2020                         struct file_struct *file = flist->files[i];
2021
2022                         if (!file->dirname)
2023                                 continue;
2024                         while (*file->dirname == '/')
2025                                 file->dirname++;
2026                         if (!*file->dirname)
2027                                 file->dirname = NULL;
2028                 }
2029         }
2030
2031         if (prune_empty_dirs && no_dups) {
2032                 int j, prev_depth = 0;
2033
2034                 prev_i = 0; /* It's OK that this isn't really true. */
2035
2036                 for (i = flist->low; i <= flist->high; i++) {
2037                         struct file_struct *fp, *file = flist->files[i];
2038
2039                         /* This temporarily abuses the F_DEPTH() value for a
2040                          * directory that is in a chain that might get pruned.
2041                          * We restore the old value if it gets a reprieve. */
2042                         if (S_ISDIR(file->mode) && F_DEPTH(file)) {
2043                                 /* Dump empty dirs when coming back down. */
2044                                 for (j = prev_depth; j >= F_DEPTH(file); j--) {
2045                                         fp = flist->files[prev_i];
2046                                         if (F_DEPTH(fp) >= 0)
2047                                                 break;
2048                                         prev_i = -F_DEPTH(fp)-1;
2049                                         clear_file(fp);
2050                                 }
2051                                 prev_depth = F_DEPTH(file);
2052                                 if (is_excluded(f_name(file, fbuf), 1,
2053                                                        ALL_FILTERS)) {
2054                                         /* Keep dirs through this dir. */
2055                                         for (j = prev_depth-1; ; j--) {
2056                                                 fp = flist->files[prev_i];
2057                                                 if (F_DEPTH(fp) >= 0)
2058                                                         break;
2059                                                 prev_i = -F_DEPTH(fp)-1;
2060                                                 F_DEPTH(fp) = j;
2061                                         }
2062                                 } else
2063                                         F_DEPTH(file) = -prev_i-1;
2064                                 prev_i = i;
2065                         } else {
2066                                 /* Keep dirs through this non-dir. */
2067                                 for (j = prev_depth; ; j--) {
2068                                         fp = flist->files[prev_i];
2069                                         if (F_DEPTH(fp) >= 0)
2070                                                 break;
2071                                         prev_i = -F_DEPTH(fp)-1;
2072                                         F_DEPTH(fp) = j;
2073                                 }
2074                         }
2075                 }
2076                 /* Dump all remaining empty dirs. */
2077                 while (1) {
2078                         struct file_struct *fp = flist->files[prev_i];
2079                         if (F_DEPTH(fp) >= 0)
2080                                 break;
2081                         prev_i = -F_DEPTH(fp)-1;
2082                         clear_file(fp);
2083                 }
2084
2085                 for (i = flist->low; i <= flist->high; i++) {
2086                         if (F_IS_ACTIVE(flist->files[i]))
2087                                 break;
2088                 }
2089                 flist->low = i;
2090                 for (i = flist->high; i >= flist->low; i--) {
2091                         if (F_IS_ACTIVE(flist->files[i]))
2092                                 break;
2093                 }
2094                 flist->high = i;
2095         }
2096 }
2097
2098 static void output_flist(struct file_list *flist)
2099 {
2100         char uidbuf[16], gidbuf[16], depthbuf[16];
2101         struct file_struct *file;
2102         const char *root, *dir, *slash, *name, *trail;
2103         const char *who = who_am_i();
2104         int i;
2105
2106         rprintf(FINFO, "[%s] flist start=%d, count=%d, low=%d, high=%d\n",
2107                 who, flist->ndx_start, flist->count, flist->low, flist->high);
2108         for (i = 0; i < flist->count; i++) {
2109                 file = flist->files[i];
2110                 if ((am_root || am_sender) && preserve_uid) {
2111                         snprintf(uidbuf, sizeof uidbuf, " uid=%ld",
2112                                  (long)F_UID(file));
2113                 } else
2114                         *uidbuf = '\0';
2115                 if (preserve_gid && F_GID(file) != GID_NONE) {
2116                         snprintf(gidbuf, sizeof gidbuf, " gid=%ld",
2117                                  (long)F_GID(file));
2118                 } else
2119                         *gidbuf = '\0';
2120                 if (!am_sender)
2121                         snprintf(depthbuf, sizeof depthbuf, "%d", F_DEPTH(file));
2122                 if (F_IS_ACTIVE(file)) {
2123                         root = am_sender ? NS(F_ROOTDIR(file)) : depthbuf;
2124                         if ((dir = file->dirname) == NULL)
2125                                 dir = slash = "";
2126                         else
2127                                 slash = "/";
2128                         name = file->basename;
2129                         trail = S_ISDIR(file->mode) ? "/" : "";
2130                 } else
2131                         root = dir = slash = name = trail = "";
2132                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
2133                         who, i, root, dir, slash, name, trail, (int)file->mode,
2134                         (double)F_LENGTH(file), uidbuf, gidbuf, file->flags);
2135         }
2136 }
2137
2138 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
2139 enum fnc_type { t_PATH, t_ITEM };
2140
2141 /* Compare the names of two file_struct entities, similar to how strcmp()
2142  * would do if it were operating on the joined strings.
2143  *
2144  * Some differences beginning with protocol_version 29: (1) directory names
2145  * are compared with an assumed trailing slash so that they compare in a
2146  * way that would cause them to sort immediately prior to any content they
2147  * may have; (2) a directory of any name compares after a non-directory of
2148  * any name at the same depth; (3) a directory with name "." compares prior
2149  * to anything else.  These changes mean that a directory and a non-dir
2150  * with the same name will not compare as equal (protocol_version >= 29).
2151  *
2152  * The dirname component can be an empty string, but the basename component
2153  * cannot (and never is in the current codebase).  The basename component
2154  * may be NULL (for a removed item), in which case it is considered to be
2155  * after any existing item. */
2156 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
2157 {
2158         int dif;
2159         const uchar *c1, *c2;
2160         enum fnc_state state1, state2;
2161         enum fnc_type type1, type2;
2162         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
2163
2164         if (!f1 || !F_IS_ACTIVE(f1)) {
2165                 if (!f2 || !F_IS_ACTIVE(f2))
2166                         return 0;
2167                 return -1;
2168         }
2169         if (!f2 || !F_IS_ACTIVE(f2))
2170                 return 1;
2171
2172         c1 = (uchar*)f1->dirname;
2173         c2 = (uchar*)f2->dirname;
2174         if (c1 == c2)
2175                 c1 = c2 = NULL;
2176         if (!c1) {
2177                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
2178                 c1 = (const uchar*)f1->basename;
2179                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
2180                         type1 = t_ITEM;
2181                         state1 = s_TRAILING;
2182                         c1 = (uchar*)"";
2183                 } else
2184                         state1 = s_BASE;
2185         } else {
2186                 type1 = t_path;
2187                 state1 = s_DIR;
2188         }
2189         if (!c2) {
2190                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
2191                 c2 = (const uchar*)f2->basename;
2192                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
2193                         type2 = t_ITEM;
2194                         state2 = s_TRAILING;
2195                         c2 = (uchar*)"";
2196                 } else
2197                         state2 = s_BASE;
2198         } else {
2199                 type2 = t_path;
2200                 state2 = s_DIR;
2201         }
2202
2203         if (type1 != type2)
2204                 return type1 == t_PATH ? 1 : -1;
2205
2206         do {
2207                 if (!*c1) {
2208                         switch (state1) {
2209                         case s_DIR:
2210                                 state1 = s_SLASH;
2211                                 c1 = (uchar*)"/";
2212                                 break;
2213                         case s_SLASH:
2214                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
2215                                 c1 = (const uchar*)f1->basename;
2216                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
2217                                         type1 = t_ITEM;
2218                                         state1 = s_TRAILING;
2219                                         c1 = (uchar*)"";
2220                                 } else
2221                                         state1 = s_BASE;
2222                                 break;
2223                         case s_BASE:
2224                                 state1 = s_TRAILING;
2225                                 if (type1 == t_PATH) {
2226                                         c1 = (uchar*)"/";
2227                                         break;
2228                                 }
2229                                 /* FALL THROUGH */
2230                         case s_TRAILING:
2231                                 type1 = t_ITEM;
2232                                 break;
2233                         }
2234                         if (*c2 && type1 != type2)
2235                                 return type1 == t_PATH ? 1 : -1;
2236                 }
2237                 if (!*c2) {
2238                         switch (state2) {
2239                         case s_DIR:
2240                                 state2 = s_SLASH;
2241                                 c2 = (uchar*)"/";
2242                                 break;
2243                         case s_SLASH:
2244                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
2245                                 c2 = (const uchar*)f2->basename;
2246                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
2247                                         type2 = t_ITEM;
2248                                         state2 = s_TRAILING;
2249                                         c2 = (uchar*)"";
2250                                 } else
2251                                         state2 = s_BASE;
2252                                 break;
2253                         case s_BASE:
2254                                 state2 = s_TRAILING;
2255                                 if (type2 == t_PATH) {
2256                                         c2 = (uchar*)"/";
2257                                         break;
2258                                 }
2259                                 /* FALL THROUGH */
2260                         case s_TRAILING:
2261                                 if (!*c1)
2262                                         return 0;
2263                                 type2 = t_ITEM;
2264                                 break;
2265                         }
2266                         if (type1 != type2)
2267                                 return type1 == t_PATH ? 1 : -1;
2268                 }
2269         } while ((dif = (int)*c1++ - (int)*c2++) == 0);
2270
2271         return dif;
2272 }
2273
2274 char *f_name_buf(void)
2275 {
2276         static char names[5][MAXPATHLEN];
2277         static unsigned int n;
2278
2279         n = (n + 1) % (sizeof names / sizeof names[0]);
2280
2281         return names[n];
2282 }
2283
2284 /* Return a copy of the full filename of a flist entry, using the indicated
2285  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
2286  * done because we checked the size when creating the file_struct entry.
2287  */
2288 char *f_name(struct file_struct *f, char *fbuf)
2289 {
2290         if (!f || !F_IS_ACTIVE(f))
2291                 return NULL;
2292
2293         if (!fbuf)
2294                 fbuf = f_name_buf();
2295
2296         if (f->dirname) {
2297                 int len = strlen(f->dirname);
2298                 memcpy(fbuf, f->dirname, len);
2299                 fbuf[len] = '/';
2300                 strlcpy(fbuf + len + 1, f->basename, MAXPATHLEN - (len + 1));
2301         } else
2302                 strlcpy(fbuf, f->basename, MAXPATHLEN);
2303
2304         return fbuf;
2305 }
2306
2307 /* Do a non-recursive scan of the named directory, possibly ignoring all
2308  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
2309  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
2310  * buffer (the functions we call will append names onto the end, but the old
2311  * dir value will be restored on exit). */
2312 struct file_list *get_dirlist(char *dirname, int dlen, int ignore_filter_rules)
2313 {
2314         struct file_list *dirlist;
2315         char dirbuf[MAXPATHLEN];
2316         int save_recurse = recurse;
2317         int save_xfer_dirs = xfer_dirs;
2318
2319         if (dlen < 0) {
2320                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
2321                 if (dlen >= MAXPATHLEN)
2322                         return NULL;
2323                 dirname = dirbuf;
2324         }
2325
2326         dirlist = flist_new(FLIST_TEMP, "get_dirlist");
2327
2328         recurse = 0;
2329         xfer_dirs = 1;
2330         send_directory(ignore_filter_rules ? -2 : -1, dirlist, -1, dirname, dlen, 0);
2331         xfer_dirs = save_xfer_dirs;
2332         recurse = save_recurse;
2333         if (do_progress)
2334                 flist_count_offset += dirlist->count;
2335
2336         clean_flist(dirlist, 0, 0);
2337
2338         if (verbose > 3)
2339                 output_flist(dirlist);
2340
2341         return dirlist;
2342 }