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