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