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