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