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