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