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