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