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