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