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