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