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