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