Moved the code that adds each file's length to stats.total_size
[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, 2003, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
22  */
23
24 #include "rsync.h"
25 #include "rounding.h"
26
27 extern int verbose;
28 extern int list_only;
29 extern int am_root;
30 extern int am_server;
31 extern int am_daemon;
32 extern int am_sender;
33 extern int incremental;
34 extern int do_progress;
35 extern int always_checksum;
36 extern int module_id;
37 extern int ignore_errors;
38 extern int numeric_ids;
39 extern int recurse;
40 extern int xfer_dirs;
41 extern int filesfrom_fd;
42 extern int one_file_system;
43 extern int copy_dirlinks;
44 extern int keep_dirlinks;
45 extern int preserve_links;
46 extern int preserve_hard_links;
47 extern int preserve_devices;
48 extern int preserve_specials;
49 extern int preserve_uid;
50 extern int preserve_gid;
51 extern int relative_paths;
52 extern int implied_dirs;
53 extern int file_extra_cnt;
54 extern int ignore_perishable;
55 extern int non_perishable_cnt;
56 extern int prune_empty_dirs;
57 extern int copy_links;
58 extern int copy_unsafe_links;
59 extern int protocol_version;
60 extern int sanitize_paths;
61 extern struct stats stats;
62
63 extern char curr_dir[MAXPATHLEN];
64
65 extern struct chmod_mode_struct *chmod_modes;
66
67 extern struct filter_list_struct filter_list;
68 extern struct filter_list_struct server_filter_list;
69
70 int io_error;
71 int checksum_len;
72 dev_t filesystem_dev; /* used to implement -x */
73
74 struct file_list *cur_flist, *first_flist, *dir_flist;
75 int send_dir_ndx = -1, send_dir_depth = 0;
76 int flist_cnt = 0; /* how many (non-tmp) file list objects exist */
77 int file_total = 0; /* total of all active items over all file-lists */
78 int flist_eof = 0; /* all the file-lists are now known */
79
80 /* The tmp_* vars are used as a cache area by make_file() to store data
81  * that the sender doesn't need to remember in its file list.  The data
82  * will survive just long enough to be used by send_file_entry(). */
83 static dev_t tmp_rdev;
84 #ifdef SUPPORT_HARD_LINKS
85 static int64 tmp_dev, tmp_ino;
86 #endif
87 static char tmp_sum[MD4_SUM_LENGTH];
88
89 static char empty_sum[MD4_SUM_LENGTH];
90 static int flist_count_offset; /* for --delete --progress */
91
92 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
93 static void output_flist(struct file_list *flist);
94
95 void init_flist(void)
96 {
97         if (verbose > 4) {
98                 rprintf(FINFO, "FILE_STRUCT_LEN=%d, EXTRA_LEN=%d\n",
99                         (int)FILE_STRUCT_LEN, (int)EXTRA_LEN);
100         }
101         checksum_len = protocol_version < 21 ? 2 : MD4_SUM_LENGTH;
102 }
103
104 static int show_filelist_p(void)
105 {
106         return verbose && xfer_dirs && !am_server && !incremental;
107 }
108
109 static void start_filelist_progress(char *kind)
110 {
111         rprintf(FCLIENT, "%s ... ", kind);
112         if (verbose > 1 || do_progress)
113                 rprintf(FCLIENT, "\n");
114         rflush(FINFO);
115 }
116
117 static void emit_filelist_progress(int count)
118 {
119         rprintf(FCLIENT, " %d files...\r", count);
120 }
121
122 static void maybe_emit_filelist_progress(int count)
123 {
124         if (do_progress && show_filelist_p() && (count % 100) == 0)
125                 emit_filelist_progress(count);
126 }
127
128 static void finish_filelist_progress(const struct file_list *flist)
129 {
130         if (do_progress) {
131                 /* This overwrites the progress line */
132                 rprintf(FINFO, "%d file%sto consider\n",
133                         flist->count, flist->count == 1 ? " " : "s ");
134         } else
135                 rprintf(FINFO, "done\n");
136 }
137
138 void show_flist_stats(void)
139 {
140         /* Nothing yet */
141 }
142
143 static void list_file_entry(struct file_struct *f)
144 {
145         char permbuf[PERMSTRING_SIZE];
146         double len;
147
148         if (!F_IS_ACTIVE(f)) {
149                 /* this can happen if duplicate names were removed */
150                 return;
151         }
152
153         permstring(permbuf, f->mode);
154         len = F_LENGTH(f);
155
156 #ifdef SUPPORT_LINKS
157         if (preserve_links && S_ISLNK(f->mode)) {
158                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
159                         permbuf, len, timestring(f->modtime),
160                         f_name(f, NULL), F_SYMLINK(f));
161         } else
162 #endif
163         {
164                 rprintf(FINFO, "%s %11.0f %s %s\n",
165                         permbuf, len, timestring(f->modtime),
166                         f_name(f, NULL));
167         }
168 }
169
170 /* Stat either a symlink or its referent, depending on the settings of
171  * copy_links, copy_unsafe_links, etc.  Returns -1 on error, 0 on success.
172  *
173  * If path is the name of a symlink, then the linkbuf buffer (which must hold
174  * MAXPATHLEN chars) will be set to the symlink's target string.
175  *
176  * The stat structure pointed to by stp will contain information about the
177  * link or the referent as appropriate, if they exist. */
178 static int readlink_stat(const char *path, STRUCT_STAT *stp, char *linkbuf)
179 {
180 #ifdef SUPPORT_LINKS
181         if (link_stat(path, stp, copy_dirlinks) < 0)
182                 return -1;
183         if (S_ISLNK(stp->st_mode)) {
184                 int llen = readlink(path, linkbuf, MAXPATHLEN - 1);
185                 if (llen < 0)
186                         return -1;
187                 linkbuf[llen] = '\0';
188                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
189                         if (verbose > 1) {
190                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
191                                         path, linkbuf);
192                         }
193                         return do_stat(path, stp);
194                 }
195         }
196         return 0;
197 #else
198         return do_stat(path, stp);
199 #endif
200 }
201
202 int link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
203 {
204 #ifdef SUPPORT_LINKS
205         if (copy_links)
206                 return do_stat(path, stp);
207         if (do_lstat(path, stp) < 0)
208                 return -1;
209         if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
210                 STRUCT_STAT st;
211                 if (do_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
212                         *stp = st;
213         }
214         return 0;
215 #else
216         return do_stat(path, stp);
217 #endif
218 }
219
220 /* This function is used to check if a file should be included/excluded
221  * from the list of files based on its name and type etc.  The value of
222  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
223 static int is_excluded(char *fname, int is_dir, int filter_level)
224 {
225 #if 0 /* This currently never happens, so avoid a useless compare. */
226         if (filter_level == NO_FILTERS)
227                 return 0;
228 #endif
229         if (fname) {
230                 /* never exclude '.', even if somebody does --exclude '*' */
231                 if (fname[0] == '.' && !fname[1])
232                         return 0;
233                 /* Handle the -R version of the '.' dir. */
234                 if (fname[0] == '/') {
235                         int len = strlen(fname);
236                         if (fname[len-1] == '.' && fname[len-2] == '/')
237                                 return 0;
238                 }
239         }
240         if (server_filter_list.head
241             && check_filter(&server_filter_list, fname, is_dir) < 0)
242                 return 1;
243         if (filter_level != ALL_FILTERS)
244                 return 0;
245         if (filter_list.head
246             && check_filter(&filter_list, fname, is_dir) < 0)
247                 return 1;
248         return 0;
249 }
250
251 static int to_wire_mode(mode_t mode)
252 {
253 #ifdef SUPPORT_LINKS
254 #if _S_IFLNK != 0120000
255         if (S_ISLNK(mode))
256                 return (mode & ~(_S_IFMT)) | 0120000;
257 #endif
258 #endif
259         return mode;
260 }
261
262 static mode_t from_wire_mode(int mode)
263 {
264 #if _S_IFLNK != 0120000
265         if ((mode & (_S_IFMT)) == 0120000)
266                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
267 #endif
268         return mode;
269 }
270
271 static void send_directory(int f, struct file_list *flist, int ndx,
272                            char *fbuf, int len, int flags);
273
274 static const char *flist_dir, *orig_dir;
275 static int flist_dir_len;
276
277
278 /**
279  * Make sure @p flist is big enough to hold at least @p flist->count
280  * entries.
281  **/
282 void flist_expand(struct file_list *flist)
283 {
284         struct file_struct **new_ptr;
285
286         if (flist->count < flist->malloced)
287                 return;
288
289         if (flist->malloced < FLIST_START)
290                 flist->malloced = FLIST_START;
291         else if (flist->malloced >= FLIST_LINEAR)
292                 flist->malloced += FLIST_LINEAR;
293         else
294                 flist->malloced *= 2;
295
296         /*
297          * In case count jumped or we are starting the list
298          * with a known size just set it.
299          */
300         if (flist->malloced < flist->count)
301                 flist->malloced = flist->count;
302
303         new_ptr = realloc_array(flist->files, struct file_struct *,
304                                 flist->malloced);
305
306         if (verbose >= 2 && flist->malloced != FLIST_START) {
307                 rprintf(FCLIENT, "[%s] expand file_list to %.0f bytes, did%s move\n",
308                     who_am_i(),
309                     (double)sizeof flist->files[0] * flist->malloced,
310                     (new_ptr == flist->files) ? " not" : "");
311         }
312
313         flist->files = new_ptr;
314
315         if (!flist->files)
316                 out_of_memory("flist_expand");
317 }
318
319 int push_flist_dir(const char *dir, int len)
320 {
321         if (dir == flist_dir)
322                 return 1;
323
324         if (!orig_dir)
325                 orig_dir = strdup(curr_dir);
326
327         if (flist_dir && !pop_dir(orig_dir)) {
328                 rsyserr(FERROR, errno, "pop_dir %s failed",
329                         full_fname(orig_dir));
330                 exit_cleanup(RERR_FILESELECT);
331         }
332
333         if (dir && !push_dir(dir, 0)) {
334                 io_error |= IOERR_GENERAL;
335                 rsyserr(FERROR, errno, "push_dir %s failed",
336                         full_fname(dir));
337                 return 0;
338         }
339
340         flist_dir = dir;
341         flist_dir_len = len >= 0 ? len : dir ? (int)strlen(dir) : 0;
342
343         return 1;
344 }
345
346 static void send_file_entry(int f, struct file_struct *file, int ndx)
347 {
348         static time_t modtime;
349         static mode_t mode;
350         static int64 dev;
351         static dev_t rdev;
352         static uint32 rdev_major;
353         static uid_t uid;
354         static gid_t gid;
355         static char *user_name, *group_name;
356         static char lastname[MAXPATHLEN];
357         char fname[MAXPATHLEN];
358         int first_hlink_ndx = -1;
359         int l1, l2;
360         int flags;
361
362         f_name(file, fname);
363
364         flags = file->flags & FLAG_TOP_DIR; /* FLAG_TOP_DIR == XMIT_TOP_DIR */
365
366         if (file->mode == mode)
367                 flags |= XMIT_SAME_MODE;
368         else
369                 mode = file->mode;
370         if ((preserve_devices && IS_DEVICE(mode))
371          || (preserve_specials && IS_SPECIAL(mode))) {
372                 if (protocol_version < 28) {
373                         if (tmp_rdev == rdev)
374                                 flags |= XMIT_SAME_RDEV_pre28;
375                         else
376                                 rdev = tmp_rdev;
377                 } else {
378                         rdev = tmp_rdev;
379                         if ((uint32)major(rdev) == rdev_major)
380                                 flags |= XMIT_SAME_RDEV_MAJOR;
381                         else
382                                 rdev_major = major(rdev);
383                         if ((uint32)minor(rdev) <= 0xFFu)
384                                 flags |= XMIT_RDEV_MINOR_IS_SMALL;
385                 }
386         } else if (protocol_version < 28)
387                 rdev = MAKEDEV(0, 0);
388         if (preserve_uid) {
389                 if (F_UID(file) == uid && *lastname)
390                         flags |= XMIT_SAME_UID;
391                 else {
392                         uid = F_UID(file);
393                         if (preserve_uid && !numeric_ids) {
394                                 user_name = add_uid(uid);
395                                 if (incremental && user_name)
396                                         flags |= XMIT_USER_NAME_FOLLOWS;
397                         }
398                 }
399         }
400         if (preserve_gid) {
401                 if (F_GID(file) == gid && *lastname)
402                         flags |= XMIT_SAME_GID;
403                 else {
404                         gid = F_GID(file);
405                         if (preserve_gid && !numeric_ids) {
406                                 group_name = add_gid(gid);
407                                 if (incremental && group_name)
408                                         flags |= XMIT_GROUP_NAME_FOLLOWS;
409                         }
410                 }
411         }
412         if (file->modtime == modtime)
413                 flags |= XMIT_SAME_TIME;
414         else
415                 modtime = file->modtime;
416
417 #ifdef SUPPORT_HARD_LINKS
418         if (tmp_dev != 0) {
419                 if (protocol_version >= 30) {
420                         struct idev_node *np = idev_node(tmp_dev, tmp_ino);
421                         first_hlink_ndx = (int32)np->data - 1;
422                         if (first_hlink_ndx < 0) {
423                                 np->data = (void*)(ndx + 1);
424                                 flags |= XMIT_HLINK_FIRST;
425                         }
426                         flags |= XMIT_HLINKED;
427                 } else {
428                         if (tmp_dev == dev) {
429                                 if (protocol_version >= 28)
430                                         flags |= XMIT_SAME_DEV_pre30;
431                         } else
432                                 dev = tmp_dev;
433                         flags |= XMIT_HLINKED;
434                 }
435         }
436 #endif
437
438         for (l1 = 0;
439             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
440             l1++) {}
441         l2 = strlen(fname+l1);
442
443         if (l1 > 0)
444                 flags |= XMIT_SAME_NAME;
445         if (l2 > 255)
446                 flags |= XMIT_LONG_NAME;
447
448         /* We must make sure we don't send a zero flag byte or the
449          * other end will terminate the flist transfer.  Note that
450          * the use of XMIT_TOP_DIR on a non-dir has no meaning, so
451          * it's harmless way to add a bit to the first flag byte. */
452         if (protocol_version >= 28) {
453                 if (!flags && !S_ISDIR(mode))
454                         flags |= XMIT_TOP_DIR;
455                 if ((flags & 0xFF00) || !flags) {
456                         flags |= XMIT_EXTENDED_FLAGS;
457                         write_shortint(f, flags);
458                 } else
459                         write_byte(f, flags);
460         } else {
461                 if (!(flags & 0xFF))
462                         flags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
463                 write_byte(f, flags);
464         }
465         if (flags & XMIT_SAME_NAME)
466                 write_byte(f, l1);
467         if (flags & XMIT_LONG_NAME)
468                 write_int(f, l2);
469         else
470                 write_byte(f, l2);
471         write_buf(f, fname + l1, l2);
472
473         if (first_hlink_ndx >= 0) {
474                 write_int(f, first_hlink_ndx);
475                 goto the_end;
476         }
477
478         write_longint(f, F_LENGTH(file));
479         if (!(flags & XMIT_SAME_TIME))
480                 write_int(f, modtime);
481         if (!(flags & XMIT_SAME_MODE))
482                 write_int(f, to_wire_mode(mode));
483         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
484                 write_int(f, uid);
485                 if (flags & XMIT_USER_NAME_FOLLOWS) {
486                         int len = strlen(user_name);
487                         write_byte(f, len);
488                         write_buf(f, user_name, len);
489                 }
490         }
491         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
492                 write_int(f, gid);
493                 if (flags & XMIT_GROUP_NAME_FOLLOWS) {
494                         int len = strlen(group_name);
495                         write_byte(f, len);
496                         write_buf(f, group_name, len);
497                 }
498         }
499         if ((preserve_devices && IS_DEVICE(mode))
500          || (preserve_specials && IS_SPECIAL(mode))) {
501                 if (protocol_version < 28) {
502                         if (!(flags & XMIT_SAME_RDEV_pre28))
503                                 write_int(f, (int)rdev);
504                 } else {
505                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
506                                 write_int(f, major(rdev));
507                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
508                                 write_byte(f, minor(rdev));
509                         else
510                                 write_int(f, minor(rdev));
511                 }
512         }
513
514 #ifdef SUPPORT_LINKS
515         if (preserve_links && S_ISLNK(mode)) {
516                 const char *sl = F_SYMLINK(file);
517                 int len = strlen(sl);
518                 write_int(f, len);
519                 write_buf(f, sl, len);
520         }
521 #endif
522
523 #ifdef SUPPORT_HARD_LINKS
524         if (tmp_dev != 0 && protocol_version < 30) {
525                 if (protocol_version < 26) {
526                         /* 32-bit dev_t and ino_t */
527                         write_int(f, (int32)dev);
528                         write_int(f, (int32)tmp_ino);
529                 } else {
530                         /* 64-bit dev_t and ino_t */
531                         if (!(flags & XMIT_SAME_DEV_pre30))
532                                 write_longint(f, dev);
533                         write_longint(f, tmp_ino);
534                 }
535         }
536 #endif
537
538         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
539                 const char *sum;
540                 if (S_ISREG(mode))
541                         sum = tmp_sum;
542                 else {
543                         /* Prior to 28, we sent a useless set of nulls. */
544                         sum = empty_sum;
545                 }
546                 write_buf(f, sum, checksum_len);
547         }
548
549   the_end:
550         strlcpy(lastname, fname, MAXPATHLEN);
551
552         if (S_ISREG(mode) || S_ISLNK(mode))
553                 stats.total_size += F_LENGTH(file);
554 }
555
556 static struct file_struct *recv_file_entry(struct file_list *flist,
557                                            int flags, int f)
558 {
559         static time_t modtime;
560         static mode_t mode;
561         static int64 dev;
562         static dev_t rdev;
563         static uint32 rdev_major;
564         static uid_t uid;
565         static gid_t gid;
566         static char lastname[MAXPATHLEN], *lastdir;
567         static int lastdir_depth, lastdir_len = -1;
568         static unsigned int del_hier_name_len = 0;
569         static int in_del_hier = 0;
570         char thisname[MAXPATHLEN];
571         unsigned int l1 = 0, l2 = 0;
572         int alloc_len, basename_len, linkname_len;
573         int extra_len = file_extra_cnt * EXTRA_LEN;
574         int first_hlink_ndx = -1;
575         OFF_T file_length;
576         const char *basename;
577         char *bp;
578         struct file_struct *file;
579
580         if (flags & XMIT_SAME_NAME)
581                 l1 = read_byte(f);
582
583         if (flags & XMIT_LONG_NAME)
584                 l2 = read_int(f);
585         else
586                 l2 = read_byte(f);
587
588         if (l2 >= MAXPATHLEN - l1) {
589                 rprintf(FERROR,
590                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s [%s]\n",
591                         flags, l1, l2, lastname, who_am_i());
592                 overflow_exit("recv_file_entry");
593         }
594
595         strlcpy(thisname, lastname, l1 + 1);
596         read_sbuf(f, &thisname[l1], l2);
597         thisname[l1 + l2] = 0;
598
599         strlcpy(lastname, thisname, MAXPATHLEN);
600
601         clean_fname(thisname, 0);
602
603         if (sanitize_paths)
604                 sanitize_path(thisname, thisname, "", 0, NULL);
605
606         if ((basename = strrchr(thisname, '/')) != NULL) {
607                 int len = basename++ - thisname;
608                 if (len != lastdir_len || memcmp(thisname, lastdir, len) != 0) {
609                         lastdir = new_array(char, len + 1);
610                         memcpy(lastdir, thisname, len);
611                         lastdir[len] = '\0';
612                         lastdir_len = len;
613                         lastdir_depth = count_dir_elements(lastdir);
614                 }
615         } else
616                 basename = thisname;
617         basename_len = strlen(basename) + 1; /* count the '\0' */
618
619 #ifdef SUPPORT_HARD_LINKS
620         if (protocol_version >= 30
621          && BITS_SETnUNSET(flags, XMIT_HLINKED, XMIT_HLINK_FIRST)) {
622                 struct file_struct *first;
623                 first_hlink_ndx = read_int(f);
624                 if (first_hlink_ndx < 0 || first_hlink_ndx >= flist->count) {
625                         rprintf(FERROR,
626                                 "hard-link reference out of range: %d (%d)\n",
627                                 first_hlink_ndx, flist->count);
628                         exit_cleanup(RERR_PROTOCOL);
629                 }
630                 first = flist->files[first_hlink_ndx];
631                 file_length = F_LENGTH(first);
632                 modtime = first->modtime;
633                 mode = first->mode;
634                 if (preserve_uid)
635                         uid = F_UID(first);
636                 if (preserve_gid)
637                         gid = F_GID(first);
638                 if ((preserve_devices && IS_DEVICE(mode))
639                  || (preserve_specials && IS_SPECIAL(mode))) {
640                         uint32 *devp = F_RDEV_P(first);
641                         rdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
642                 }
643                 if (preserve_links && S_ISLNK(mode))
644                         linkname_len = strlen(F_SYMLINK(first)) + 1;
645                 else
646                         linkname_len = 0;
647                 goto create_object;
648         }
649 #endif
650
651         file_length = read_longint(f);
652         if (!(flags & XMIT_SAME_TIME))
653                 modtime = (time_t)read_int(f);
654         if (!(flags & XMIT_SAME_MODE))
655                 mode = from_wire_mode(read_int(f));
656
657         if (chmod_modes && !S_ISLNK(mode))
658                 mode = tweak_mode(mode, chmod_modes);
659
660         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
661                 uid = (uid_t)read_int(f);
662                 if (flags & XMIT_USER_NAME_FOLLOWS)
663                         uid = recv_user_name(f, uid);
664                 else if (incremental && am_root && !numeric_ids)
665                         uid = match_uid(uid);
666         }
667         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
668                 gid = (gid_t)read_int(f);
669                 if (flags & XMIT_GROUP_NAME_FOLLOWS)
670                         gid = recv_group_name(f, gid);
671                 else if (incremental && (!am_root || !numeric_ids))
672                         gid = match_gid(gid);
673         }
674
675         if ((preserve_devices && IS_DEVICE(mode))
676          || (preserve_specials && IS_SPECIAL(mode))) {
677                 if (protocol_version < 28) {
678                         if (!(flags & XMIT_SAME_RDEV_pre28))
679                                 rdev = (dev_t)read_int(f);
680                 } else {
681                         uint32 rdev_minor;
682                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
683                                 rdev_major = read_int(f);
684                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
685                                 rdev_minor = read_byte(f);
686                         else
687                                 rdev_minor = read_int(f);
688                         rdev = MAKEDEV(rdev_major, rdev_minor);
689                 }
690                 extra_len += 2 * EXTRA_LEN;
691                 file_length = 0;
692         } else if (protocol_version < 28)
693                 rdev = MAKEDEV(0, 0);
694
695 #ifdef SUPPORT_LINKS
696         if (preserve_links && S_ISLNK(mode)) {
697                 linkname_len = read_int(f) + 1; /* count the '\0' */
698                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
699                         rprintf(FERROR, "overflow: linkname_len=%d\n",
700                                 linkname_len - 1);
701                         overflow_exit("recv_file_entry");
702                 }
703         }
704         else
705 #endif
706                 linkname_len = 0;
707
708 #ifdef SUPPORT_HARD_LINKS
709   create_object:
710         if (preserve_hard_links) {
711                 if (protocol_version < 28 && S_ISREG(mode))
712                         flags |= XMIT_HLINKED;
713                 if (flags & XMIT_HLINKED)
714                         extra_len += EXTRA_LEN;
715         }
716 #endif
717
718         if (always_checksum && S_ISREG(mode))
719                 extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
720
721         if (file_length > 0xFFFFFFFFu && S_ISREG(mode))
722                 extra_len += EXTRA_LEN;
723
724 #if EXTRA_ROUNDING > 0
725         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
726                 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
727 #endif
728
729         if (incremental && S_ISDIR(mode)) {
730                 if (one_file_system) {
731                         /* Room to save the dir's device for -x */
732                         extra_len += 2 * EXTRA_LEN;
733                 }
734                 flist = dir_flist;
735         }
736
737         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
738                   + linkname_len;
739         bp = pool_alloc(flist->file_pool, alloc_len, "recv_file_entry");
740
741         memset(bp, 0, extra_len + FILE_STRUCT_LEN);
742         bp += extra_len;
743         file = (struct file_struct *)bp;
744         bp += FILE_STRUCT_LEN;
745
746         memcpy(bp, basename, basename_len);
747         bp += basename_len + linkname_len; /* skip space for symlink too */
748
749 #ifdef SUPPORT_HARD_LINKS
750         if (flags & XMIT_HLINKED)
751                 file->flags |= FLAG_HLINKED;
752 #endif
753         file->modtime = modtime;
754         file->len32 = (uint32)file_length;
755         if (file_length > 0xFFFFFFFFu && S_ISREG(mode)) {
756                 file->flags |= FLAG_LENGTH64;
757                 OPT_EXTRA(file, 0)->unum = (uint32)(file_length >> 32);
758         }
759         file->mode = mode;
760         if (preserve_uid)
761                 F_OWNER(file) = uid;
762         if (preserve_gid)
763                 F_GROUP(file) = gid;
764
765         if (basename != thisname) {
766                 file->dirname = lastdir;
767                 F_DEPTH(file) = lastdir_depth + 1;
768         } else
769                 F_DEPTH(file) = 1;
770
771         if (S_ISDIR(mode)) {
772                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
773                         F_DEPTH(file)--;
774                 if (flags & XMIT_TOP_DIR) {
775                         in_del_hier = recurse;
776                         del_hier_name_len = F_DEPTH(file) == 0 ? 0 : l1 + l2;
777                         if (relative_paths && del_hier_name_len > 2
778                             && lastname[del_hier_name_len-1] == '.'
779                             && lastname[del_hier_name_len-2] == '/')
780                                 del_hier_name_len -= 2;
781                         file->flags |= FLAG_TOP_DIR | FLAG_XFER_DIR;
782                 } else if (in_del_hier) {
783                         if (!relative_paths || !del_hier_name_len
784                          || (l1 >= del_hier_name_len
785                           && lastname[del_hier_name_len] == '/'))
786                                 file->flags |= FLAG_XFER_DIR;
787                         else
788                                 in_del_hier = 0;
789                 }
790         }
791
792         if ((preserve_devices && IS_DEVICE(mode))
793          || (preserve_specials && IS_SPECIAL(mode))) {
794                 uint32 *devp = F_RDEV_P(file);
795                 DEV_MAJOR(devp) = major(rdev);
796                 DEV_MINOR(devp) = minor(rdev);
797         }
798
799 #ifdef SUPPORT_LINKS
800         if (linkname_len) {
801                 bp = (char*)file->basename + basename_len;
802                 if (first_hlink_ndx >= 0) {
803                         struct file_struct *first = flist->files[first_hlink_ndx];
804                         memcpy(bp, F_SYMLINK(first), linkname_len);
805                 } else
806                         read_sbuf(f, bp, linkname_len - 1);
807                 if (sanitize_paths)
808                         sanitize_path(bp, bp, "", lastdir_depth, NULL);
809         }
810 #endif
811
812 #ifdef SUPPORT_HARD_LINKS
813         if (preserve_hard_links && flags & XMIT_HLINKED) {
814                 if (protocol_version >= 30) {
815                         F_HL_GNUM(file) = flags & XMIT_HLINK_FIRST
816                                         ? flist->count : first_hlink_ndx;
817                 } else {
818                         static int32 cnt = 0;
819                         struct idev_node *np;
820                         int64 ino;
821                         int32 ndx;
822                         if (protocol_version < 26) {
823                                 dev = read_int(f);
824                                 ino = read_int(f);
825                         } else {
826                                 if (!(flags & XMIT_SAME_DEV_pre30))
827                                         dev = read_longint(f);
828                                 ino = read_longint(f);
829                         }
830                         np = idev_node(dev, ino);
831                         ndx = (int32)np->data - 1;
832                         if (ndx < 0) {
833                                 ndx = cnt++;
834                                 np->data = (void*)cnt;
835                         }
836                         F_HL_GNUM(file) = ndx;
837                 }
838         }
839 #endif
840
841         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
842                 if (S_ISREG(mode))
843                         bp = (char*)F_SUM(file);
844                 else {
845                         /* Prior to 28, we get a useless set of nulls. */
846                         bp = tmp_sum;
847                 }
848                 if (first_hlink_ndx >= 0) {
849                         struct file_struct *first = flist->files[first_hlink_ndx];
850                         memcpy(bp, F_SUM(first), checksum_len);
851                 } else
852                         read_buf(f, bp, checksum_len);
853         }
854
855         if (S_ISREG(mode) || S_ISLNK(mode))
856                 stats.total_size += file_length;
857
858         return file;
859 }
860
861 /**
862  * Create a file_struct for a named file by reading its stat()
863  * information and performing extensive checks against global
864  * options.
865  *
866  * @return the new file, or NULL if there was an error or this file
867  * should be excluded.
868  *
869  * @todo There is a small optimization opportunity here to avoid
870  * stat()ing the file in some circumstances, which has a certain cost.
871  * We are called immediately after doing readdir(), and so we may
872  * already know the d_type of the file.  We could for example avoid
873  * statting directories if we're not recursing, but this is not a very
874  * important case.  Some systems may not have d_type.
875  **/
876 struct file_struct *make_file(const char *fname, struct file_list *flist,
877                               STRUCT_STAT *stp, int flags, int filter_level)
878 {
879         static char *lastdir;
880         static int lastdir_len = -1;
881         struct file_struct *file;
882         STRUCT_STAT st;
883         char thisname[MAXPATHLEN];
884         char linkname[MAXPATHLEN];
885         int alloc_len, basename_len, linkname_len;
886         int extra_len = file_extra_cnt * EXTRA_LEN;
887         const char *basename;
888         char *bp;
889
890         if (strlcpy(thisname, fname, sizeof thisname)
891             >= sizeof thisname - flist_dir_len) {
892                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
893                 return NULL;
894         }
895         clean_fname(thisname, 0);
896         if (sanitize_paths)
897                 sanitize_path(thisname, thisname, "", 0, NULL);
898
899         if (stp && S_ISDIR(stp->st_mode)) {
900                 st = *stp; /* Needed for "symlink/." with --relative. */
901                 *linkname = '\0'; /* make IBM code checker happy */
902         } else if (readlink_stat(thisname, &st, linkname) != 0) {
903                 int save_errno = errno;
904                 /* See if file is excluded before reporting an error. */
905                 if (filter_level != NO_FILTERS
906                  && (is_excluded(thisname, 0, filter_level)
907                   || is_excluded(thisname, 1, filter_level))) {
908                         if (ignore_perishable && save_errno != ENOENT)
909                                 non_perishable_cnt++;
910                         return NULL;
911                 }
912                 if (save_errno == ENOENT) {
913 #ifdef SUPPORT_LINKS
914                         /* Avoid "vanished" error if symlink points nowhere. */
915                         if (copy_links && do_lstat(thisname, &st) == 0
916                             && S_ISLNK(st.st_mode)) {
917                                 io_error |= IOERR_GENERAL;
918                                 rprintf(FERROR, "symlink has no referent: %s\n",
919                                         full_fname(thisname));
920                         } else
921 #endif
922                         {
923                                 enum logcode c = am_daemon && protocol_version < 28
924                                     ? FERROR : FINFO;
925                                 io_error |= IOERR_VANISHED;
926                                 rprintf(c, "file has vanished: %s\n",
927                                         full_fname(thisname));
928                         }
929                 } else {
930                         io_error |= IOERR_GENERAL;
931                         rsyserr(FERROR, save_errno, "readlink %s failed",
932                                 full_fname(thisname));
933                 }
934                 return NULL;
935         }
936
937         /* backup.c calls us with filter_level set to NO_FILTERS. */
938         if (filter_level == NO_FILTERS)
939                 goto skip_filters;
940
941         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
942                 rprintf(FINFO, "skipping directory %s\n", thisname);
943                 return NULL;
944         }
945
946         /* -x only affects directories because we need to avoid recursing
947          * into a mount-point directory, not to avoid copying a symlinked
948          * file if -L (or similar) was specified. */
949         if (one_file_system && st.st_dev != filesystem_dev
950          && S_ISDIR(st.st_mode)) {
951                 if (one_file_system > 1) {
952                         if (verbose > 2) {
953                                 rprintf(FINFO, "skipping mount-point dir %s\n",
954                                         thisname);
955                         }
956                         return NULL;
957                 }
958                 flags |= FLAG_MOUNT_DIR;
959         }
960
961         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level)) {
962                 if (ignore_perishable)
963                         non_perishable_cnt++;
964                 return NULL;
965         }
966
967         if (lp_ignore_nonreadable(module_id)) {
968 #ifdef SUPPORT_LINKS
969                 if (!S_ISLNK(st.st_mode))
970 #endif
971                         if (access(thisname, R_OK) != 0)
972                                 return NULL;
973         }
974
975   skip_filters:
976
977         /* Only divert a directory in the main transfer. */
978         if (flist && flist->prev && S_ISDIR(st.st_mode)
979          && flags & FLAG_DIVERT_DIRS) {
980                 flist = dir_flist;
981                 /* Room for parent/sibling/next-child info. */
982                 extra_len += 3 * EXTRA_LEN;
983         }
984
985         if (verbose > 2) {
986                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
987                         who_am_i(), thisname, filter_level);
988         }
989
990         if ((basename = strrchr(thisname, '/')) != NULL) {
991                 int len = basename++ - thisname;
992                 if (len != lastdir_len || memcmp(thisname, lastdir, len) != 0) {
993                         lastdir = new_array(char, len + 1);
994                         memcpy(lastdir, thisname, len);
995                         lastdir[len] = '\0';
996                         lastdir_len = len;
997                 }
998         } else
999                 basename = thisname;
1000         basename_len = strlen(basename) + 1; /* count the '\0' */
1001
1002 #ifdef SUPPORT_LINKS
1003         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
1004 #else
1005         linkname_len = 0;
1006 #endif
1007
1008         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode))
1009                 extra_len += EXTRA_LEN;
1010
1011 #if EXTRA_ROUNDING > 0
1012         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
1013                 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
1014 #endif
1015
1016         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
1017                   + linkname_len;
1018         if (flist)
1019                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
1020         else {
1021                 if (!(bp = new_array(char, alloc_len)))
1022                         out_of_memory("make_file");
1023         }
1024
1025         memset(bp, 0, extra_len + FILE_STRUCT_LEN);
1026         bp += extra_len;
1027         file = (struct file_struct *)bp;
1028         bp += FILE_STRUCT_LEN;
1029
1030         memcpy(bp, basename, basename_len);
1031         bp += basename_len + linkname_len; /* skip space for symlink too */
1032
1033 #ifdef SUPPORT_HARD_LINKS
1034         if (preserve_hard_links && flist && flist->prev) {
1035                 if (protocol_version >= 28
1036                  ? (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
1037                  : S_ISREG(st.st_mode)) {
1038                         tmp_dev = st.st_dev;
1039                         tmp_ino = st.st_ino;
1040                 } else
1041                         tmp_dev = 0;
1042         }
1043 #endif
1044
1045 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1046         if (IS_DEVICE(st.st_mode) || IS_SPECIAL(st.st_mode)) {
1047                 tmp_rdev = st.st_rdev;
1048                 st.st_size = 0;
1049         }
1050 #endif
1051
1052         file->flags = flags;
1053         file->modtime = st.st_mtime;
1054         file->len32 = (uint32)st.st_size;
1055         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode)) {
1056                 file->flags |= FLAG_LENGTH64;
1057                 OPT_EXTRA(file, 0)->unum = (uint32)(st.st_size >> 32);
1058         }
1059         file->mode = st.st_mode;
1060         if (preserve_uid)
1061                 F_OWNER(file) = st.st_uid;
1062         if (preserve_gid)
1063                 F_GROUP(file) = st.st_gid;
1064
1065         if (basename != thisname)
1066                 file->dirname = lastdir;
1067
1068 #ifdef SUPPORT_LINKS
1069         if (linkname_len) {
1070                 bp = (char*)file->basename + basename_len;
1071                 memcpy(bp, linkname, linkname_len);
1072         }
1073 #endif
1074
1075         if (always_checksum && am_sender && S_ISREG(st.st_mode))
1076                 file_checksum(thisname, tmp_sum, st.st_size);
1077
1078         F_ROOTDIR(file) = flist_dir;
1079
1080         /* This code is only used by the receiver when it is building
1081          * a list of files for a delete pass. */
1082         if (keep_dirlinks && linkname_len && flist) {
1083                 STRUCT_STAT st2;
1084                 int save_mode = file->mode;
1085                 file->mode = S_IFDIR; /* Find a directory with our name. */
1086                 if (flist_find(dir_flist, file) >= 0
1087                     && do_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
1088                         file->modtime = st2.st_mtime;
1089                         file->len32 = 0;
1090                         file->mode = st2.st_mode;
1091                         if (preserve_uid)
1092                                 F_OWNER(file) = st2.st_uid;
1093                         if (preserve_gid)
1094                                 F_GROUP(file) = st2.st_gid;
1095                 } else
1096                         file->mode = save_mode;
1097         }
1098
1099         if (basename_len == 0+1)
1100                 return NULL;
1101
1102         if (incremental && flist == dir_flist) {
1103                 flist_expand(flist);
1104                 flist->files[flist->count++] = file;
1105         }
1106
1107         return file;
1108 }
1109
1110 /* Only called for temporary file_struct entries created by make_file(). */
1111 void unmake_file(struct file_struct *file)
1112 {
1113         int extra_cnt = file_extra_cnt + LEN64_BUMP(file);
1114 #if EXTRA_ROUNDING > 0
1115         if (extra_cnt & EXTRA_ROUNDING)
1116                 extra_cnt = (extra_cnt | EXTRA_ROUNDING) + 1;
1117 #endif
1118         free(REQ_EXTRA(file, extra_cnt));
1119 }
1120
1121 static struct file_struct *send_file_name(int f, struct file_list *flist,
1122                                           char *fname, STRUCT_STAT *stp,
1123                                           int flags, int filter_flags)
1124 {
1125         struct file_struct *file;
1126
1127         file = make_file(fname, flist, stp, flags, filter_flags);
1128         if (!file)
1129                 return NULL;
1130
1131         if (chmod_modes && !S_ISLNK(file->mode))
1132                 file->mode = tweak_mode(file->mode, chmod_modes);
1133
1134         maybe_emit_filelist_progress(flist->count + flist_count_offset);
1135
1136         flist_expand(flist);
1137         flist->files[flist->count++] = file;
1138         if (f >= 0)
1139                 send_file_entry(f, file, flist->count - 1);
1140         return file;
1141 }
1142
1143 static void send_if_directory(int f, struct file_list *flist,
1144                               struct file_struct *file,
1145                               char *fbuf, unsigned int ol,
1146                               int flags)
1147 {
1148         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
1149
1150         if (S_ISDIR(file->mode)
1151             && !(file->flags & FLAG_MOUNT_DIR) && f_name(file, fbuf)) {
1152                 void *save_filters;
1153                 unsigned int len = strlen(fbuf);
1154                 if (len > 1 && fbuf[len-1] == '/')
1155                         fbuf[--len] = '\0';
1156                 if (len >= MAXPATHLEN - 1) {
1157                         io_error |= IOERR_GENERAL;
1158                         rprintf(FERROR, "skipping long-named directory: %s\n",
1159                                 full_fname(fbuf));
1160                         return;
1161                 }
1162                 save_filters = push_local_filters(fbuf, len);
1163                 send_directory(f, flist, -1, fbuf, len, flags);
1164                 pop_local_filters(save_filters);
1165                 fbuf[ol] = '\0';
1166                 if (is_dot_dir)
1167                         fbuf[ol-1] = '.';
1168         }
1169 }
1170
1171 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1172 {
1173         return f_name_cmp(*file1, *file2);
1174 }
1175
1176 /* We take an entire set of sibling dirs from dir_flist (start <= ndx <= end),
1177  * sort them by name, and link them into the tree, setting the appropriate
1178  * parent/child/sibling pointers. */
1179 static void add_dirs_to_tree(int parent_ndx, int start, int end)
1180 {
1181         int i;
1182         int32 *dp = NULL;
1183         int32 *parent_dp = parent_ndx < 0 ? NULL
1184                          : F_DIRNODE_P(dir_flist->files[parent_ndx]);
1185
1186         qsort(dir_flist->files + start, end - start + 1,
1187               sizeof dir_flist->files[0], (int (*)())file_compare);
1188
1189         for (i = start; i <= end; i++) {
1190                 struct file_struct *file = dir_flist->files[i];
1191                 if (!(file->flags & FLAG_XFER_DIR)
1192                  || file->flags & FLAG_MOUNT_DIR)
1193                         continue;
1194                 if (dp)
1195                         DIR_NEXT_SIBLING(dp) = i;
1196                 else if (parent_dp)
1197                         DIR_FIRST_CHILD(parent_dp) = i;
1198                 else
1199                         send_dir_ndx = i;
1200                 dp = F_DIRNODE_P(file);
1201                 DIR_PARENT(dp) = parent_ndx;
1202                 DIR_FIRST_CHILD(dp) = -1;
1203         }
1204         if (dp)
1205                 DIR_NEXT_SIBLING(dp) = -1;
1206 }
1207
1208 /* This function is normally called by the sender, but the receiving side also
1209  * calls it from get_dirlist() with f set to -1 so that we just construct the
1210  * file list in memory without sending it over the wire.  Also, get_dirlist()
1211  * might call this with f set to -2, which also indicates that local filter
1212  * rules should be ignored. */
1213 static void send_directory(int f, struct file_list *flist, int parent_ndx,
1214                            char *fbuf, int len, int flags)
1215 {
1216         struct dirent *di;
1217         unsigned remainder;
1218         char *p;
1219         DIR *d;
1220         int divert_dirs = (flags & FLAG_DIVERT_DIRS) != 0;
1221         int start = divert_dirs ? dir_flist->count : flist->count;
1222         int filter_flags = f == -2 ? SERVER_FILTERS : ALL_FILTERS;
1223
1224         assert(flist != NULL);
1225
1226         if (!(d = opendir(fbuf))) {
1227                 io_error |= IOERR_GENERAL;
1228                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1229                 return;
1230         }
1231
1232         p = fbuf + len;
1233         if (len != 1 || *fbuf != '/')
1234                 *p++ = '/';
1235         *p = '\0';
1236         remainder = MAXPATHLEN - (p - fbuf);
1237
1238         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1239                 char *dname = d_name(di);
1240                 if (dname[0] == '.' && (dname[1] == '\0'
1241                     || (dname[1] == '.' && dname[2] == '\0')))
1242                         continue;
1243                 if (strlcpy(p, dname, remainder) >= remainder) {
1244                         io_error |= IOERR_GENERAL;
1245                         rprintf(FINFO,
1246                                 "cannot send long-named file %s\n",
1247                                 full_fname(fbuf));
1248                         continue;
1249                 }
1250
1251                 send_file_name(f, flist, fbuf, NULL, flags, filter_flags);
1252         }
1253
1254         fbuf[len] = '\0';
1255
1256         if (errno) {
1257                 io_error |= IOERR_GENERAL;
1258                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1259         }
1260
1261         closedir(d);
1262
1263         if (f < 0)
1264                 return;
1265
1266         if (divert_dirs)
1267                 add_dirs_to_tree(parent_ndx, start, dir_flist->count - 1);
1268         else if (recurse) {
1269                 int i, end = flist->count - 1;
1270                 /* send_if_directory() bumps flist->count, so use "end". */
1271                 for (i = start; i <= end; i++)
1272                         send_if_directory(f, flist, flist->files[i], fbuf, len, flags);
1273         }
1274 }
1275
1276 void send_extra_file_list(int f, int at_least)
1277 {
1278         char fbuf[MAXPATHLEN];
1279         struct file_list *flist;
1280         int64 start_write;
1281         int past_and_present, save_io_error = io_error;
1282
1283         if (send_dir_ndx < 0)
1284                 return;
1285
1286         /* Keep sending data until we have the requested number of
1287          * files in the upcoming file-lists. */
1288         past_and_present = cur_flist->ndx_start - first_flist->ndx_start
1289                          + cur_flist->count;
1290         while (file_total - past_and_present < at_least) {
1291                 struct file_struct *file = dir_flist->files[send_dir_ndx];
1292                 int32 *dp;
1293                 int dlen;
1294
1295                 f_name(file, fbuf);
1296                 dlen = strlen(fbuf);
1297
1298                 if (F_ROOTDIR(file) != flist_dir) {
1299                         if (!push_flist_dir(F_ROOTDIR(file), -1))
1300                                 exit_cleanup(RERR_FILESELECT);
1301                 }
1302
1303                 flist = flist_new(0, "send_extra_file_list");
1304                 start_write = stats.total_written;
1305
1306                 write_ndx(f, NDX_FLIST_OFFSET - send_dir_ndx);
1307                 change_local_filter_dir(fbuf, dlen, send_dir_depth);
1308                 send_directory(f, flist, send_dir_ndx, fbuf, dlen, FLAG_DIVERT_DIRS | FLAG_XFER_DIR);
1309                 write_byte(f, 0);
1310
1311                 clean_flist(flist, 0, 0);
1312                 file_total += flist->count;
1313                 stats.flist_size += stats.total_written - start_write;
1314                 stats.num_files += flist->count;
1315                 if (verbose > 3)
1316                         output_flist(flist);
1317
1318                 dp = F_DIRNODE_P(file);
1319                 if (DIR_FIRST_CHILD(dp) >= 0) {
1320                         send_dir_ndx = DIR_FIRST_CHILD(dp);
1321                         send_dir_depth++;
1322                 } else {
1323                         while (DIR_NEXT_SIBLING(dp) < 0) {
1324                                 if ((send_dir_ndx = DIR_PARENT(dp)) < 0) {
1325                                         write_ndx(f, NDX_FLIST_EOF);
1326                                         flist_eof = 1;
1327                                         change_local_filter_dir(NULL, 0, 0);
1328                                         goto finish;
1329                                 }
1330                                 send_dir_depth--;
1331                                 file = dir_flist->files[send_dir_ndx];
1332                                 dp = F_DIRNODE_P(file);
1333                         }
1334                         send_dir_ndx = DIR_NEXT_SIBLING(dp);
1335                 }
1336         }
1337
1338   finish:
1339         if (io_error != save_io_error && !ignore_errors)
1340                 send_msg_int(MSG_IO_ERROR, io_error);
1341 }
1342
1343 struct file_list *send_file_list(int f, int argc, char *argv[])
1344 {
1345         int len;
1346         STRUCT_STAT st;
1347         char *p, *dir;
1348         char lastpath[MAXPATHLEN] = "";
1349         struct file_list *flist;
1350         struct timeval start_tv, end_tv;
1351         int64 start_write;
1352         int use_ff_fd = 0;
1353         int flags, disable_buffering;
1354
1355         rprintf(FLOG, "building file list\n");
1356         if (show_filelist_p())
1357                 start_filelist_progress("building file list");
1358         else if (incremental && verbose && !am_server)
1359                 rprintf(FCLIENT, "sending incremental file list\n");
1360
1361         start_write = stats.total_written;
1362         gettimeofday(&start_tv, NULL);
1363
1364 #ifdef SUPPORT_HARD_LINKS
1365         if (preserve_hard_links && protocol_version >= 30 && !cur_flist)
1366                 init_hard_links();
1367 #endif
1368
1369         flist = cur_flist = flist_new(0, "send_file_list");
1370         if (incremental) {
1371                 dir_flist = flist_new(FLIST_TEMP, "send_file_list");
1372                 flags = FLAG_DIVERT_DIRS;
1373         } else {
1374                 dir_flist = cur_flist;
1375                 flags = 0;
1376         }
1377
1378         disable_buffering = io_start_buffering_out(f);
1379         if (filesfrom_fd >= 0) {
1380                 if (argv[0] && !push_dir(argv[0], 0)) {
1381                         rsyserr(FERROR, errno, "push_dir %s failed",
1382                                 full_fname(argv[0]));
1383                         exit_cleanup(RERR_FILESELECT);
1384                 }
1385                 use_ff_fd = 1;
1386         }
1387
1388         while (1) {
1389                 char fbuf[MAXPATHLEN];
1390                 char *fn;
1391                 int is_dot_dir;
1392
1393                 if (use_ff_fd) {
1394                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1395                                 break;
1396                         sanitize_path(fbuf, fbuf, "", 0, NULL);
1397                 } else {
1398                         if (argc-- == 0)
1399                                 break;
1400                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1401                         if (sanitize_paths)
1402                                 sanitize_path(fbuf, fbuf, "", 0, NULL);
1403                 }
1404
1405                 len = strlen(fbuf);
1406                 if (relative_paths) {
1407                         /* We clean up fbuf below. */
1408                         is_dot_dir = 0;
1409                 } else if (!len || fbuf[len - 1] == '/') {
1410                         if (len == 2 && fbuf[0] == '.') {
1411                                 /* Turn "./" into just "." rather than "./." */
1412                                 fbuf[1] = '\0';
1413                         } else {
1414                                 if (len + 1 >= MAXPATHLEN)
1415                                         overflow_exit("send_file_list");
1416                                 fbuf[len++] = '.';
1417                                 fbuf[len] = '\0';
1418                         }
1419                         is_dot_dir = 1;
1420                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1421                     && (len == 2 || fbuf[len-3] == '/')) {
1422                         if (len + 2 >= MAXPATHLEN)
1423                                 overflow_exit("send_file_list");
1424                         fbuf[len++] = '/';
1425                         fbuf[len++] = '.';
1426                         fbuf[len] = '\0';
1427                         is_dot_dir = 1;
1428                 } else {
1429                         is_dot_dir = fbuf[len-1] == '.'
1430                                    && (len == 1 || fbuf[len-2] == '/');
1431                 }
1432
1433                 if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
1434                         io_error |= IOERR_GENERAL;
1435                         rsyserr(FERROR, errno, "link_stat %s failed",
1436                                 full_fname(fbuf));
1437                         continue;
1438                 }
1439
1440                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1441                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1442                         continue;
1443                 }
1444
1445                 dir = NULL;
1446
1447                 if (!relative_paths) {
1448                         p = strrchr(fbuf, '/');
1449                         if (p) {
1450                                 *p = '\0';
1451                                 if (p == fbuf)
1452                                         dir = "/";
1453                                 else
1454                                         dir = fbuf;
1455                                 len -= p - fbuf + 1;
1456                                 fn = p + 1;
1457                         } else
1458                                 fn = fbuf;
1459                 } else {
1460                         if ((p = strstr(fbuf, "/./")) != NULL) {
1461                                 *p = '\0';
1462                                 if (p == fbuf)
1463                                         dir = "/";
1464                                 else
1465                                         dir = fbuf;
1466                                 len -= p - fbuf + 3;
1467                                 fn = p + 3;
1468                         } else
1469                                 fn = fbuf;
1470                         /* Get rid of trailing "/" and "/.". */
1471                         while (len) {
1472                                 if (fn[len - 1] == '/') {
1473                                         is_dot_dir = 1;
1474                                         if (!--len && !dir) {
1475                                                 len++;
1476                                                 break;
1477                                         }
1478                                 }
1479                                 else if (len >= 2 && fn[len - 1] == '.'
1480                                                   && fn[len - 2] == '/') {
1481                                         is_dot_dir = 1;
1482                                         if (!(len -= 2) && !dir) {
1483                                                 len++;
1484                                                 break;
1485                                         }
1486                                 } else
1487                                         break;
1488                         }
1489                         if (len == 1 && fn[0] == '/')
1490                                 fn[len++] = '.';
1491                         fn[len] = '\0';
1492                         /* Reject a ".." dir in the active part of the path. */
1493                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1494                                 if ((p[2] == '/' || p[2] == '\0')
1495                                  && (p == fn || p[-1] == '/')) {
1496                                         rprintf(FERROR,
1497                                             "found \"..\" dir in relative path: %s\n",
1498                                             fbuf);
1499                                         exit_cleanup(RERR_SYNTAX);
1500                                 }
1501                         }
1502                 }
1503
1504                 if (!*fn) {
1505                         len = 1;
1506                         fn = ".";
1507                 }
1508
1509                 if (dir && *dir) {
1510                         static const char *lastdir;
1511                         static int lastdir_len = -1;
1512                         int len = strlen(dir);
1513
1514                         if (len != lastdir_len || memcmp(lastdir, dir, len) != 0) {
1515                                 if (!push_flist_dir(strdup(dir), len))
1516                                         goto push_error;
1517                                 lastdir = flist_dir;
1518                                 lastdir_len = flist_dir_len;
1519                         } else if (!push_flist_dir(lastdir, lastdir_len)) {
1520                           push_error:
1521                                 io_error |= IOERR_GENERAL;
1522                                 rsyserr(FERROR, errno, "push_dir %s failed",
1523                                         full_fname(dir));
1524                                 continue;
1525                         }
1526                 }
1527
1528                 if (fn != fbuf)
1529                         memmove(fbuf, fn, len + 1);
1530
1531                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1532                         /* Send the implied directories at the start of the
1533                          * source spec, so we get their permissions right. */
1534                         char *lp = lastpath, *slash = fbuf;
1535                         *p = '\0';
1536                         /* Skip any initial directories in our path that we
1537                          * have in common with lastpath. */
1538                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1539                                 if (*fn == '/')
1540                                         slash = fn;
1541                         }
1542                         *p = '/';
1543                         if (fn != p || (*lp && *lp != '/')) {
1544                                 int save_copy_links = copy_links;
1545                                 int save_xfer_dirs = xfer_dirs;
1546                                 int dir_flags = incremental ? FLAG_DIVERT_DIRS : 0;
1547                                 copy_links |= copy_unsafe_links;
1548                                 xfer_dirs = 1;
1549                                 while ((slash = strchr(slash+1, '/')) != 0) {
1550                                         *slash = '\0';
1551                                         send_file_name(f, flist, fbuf, NULL,
1552                                                        dir_flags, ALL_FILTERS);
1553                                         *slash = '/';
1554                                 }
1555                                 copy_links = save_copy_links;
1556                                 xfer_dirs = save_xfer_dirs;
1557                                 *p = '\0';
1558                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1559                                 *p = '/';
1560                         }
1561                 }
1562
1563                 if (one_file_system)
1564                         filesystem_dev = st.st_dev;
1565
1566                 if (recurse || (xfer_dirs && is_dot_dir)) {
1567                         struct file_struct *file;
1568                         int top_flags = FLAG_TOP_DIR | FLAG_XFER_DIR
1569                                       | (is_dot_dir ? 0 : flags)
1570                                       | (incremental ? FLAG_DIVERT_DIRS : 0);
1571                         file = send_file_name(f, flist, fbuf, &st,
1572                                               top_flags, ALL_FILTERS);
1573                         if (file && !incremental)
1574                                 send_if_directory(f, flist, file, fbuf, len, flags);
1575                 } else
1576                         send_file_name(f, flist, fbuf, &st, flags, ALL_FILTERS);
1577         }
1578
1579         gettimeofday(&end_tv, NULL);
1580         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1581                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1582         if (stats.flist_buildtime == 0)
1583                 stats.flist_buildtime = 1;
1584         start_tv = end_tv;
1585
1586         write_byte(f, 0); /* Indicate end of file list */
1587
1588 #ifdef SUPPORT_HARD_LINKS
1589         if (preserve_hard_links && protocol_version >= 30 && !incremental)
1590                 idev_destroy();
1591 #endif
1592
1593         if (show_filelist_p())
1594                 finish_filelist_progress(flist);
1595
1596         gettimeofday(&end_tv, NULL);
1597         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1598                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1599
1600         /* Sort the list without removing any duplicates in non-incremental
1601          * mode.  This allows the receiving side to ask for whatever name it
1602          * kept.  For incremental mode, the sender also removes duplicates
1603          * in this initial file-list so that it avoids re-sending duplicated
1604          * directories. */
1605         clean_flist(flist, 0, incremental);
1606         file_total += flist->count;
1607
1608         if (!numeric_ids && !incremental)
1609                 send_uid_list(f);
1610
1611         /* send the io_error flag */
1612         if (protocol_version < 30)
1613                 write_int(f, ignore_errors ? 0 : io_error);
1614         else if (io_error && !ignore_errors)
1615                 send_msg_int(MSG_IO_ERROR, io_error);
1616
1617         if (disable_buffering)
1618                 io_end_buffering_out();
1619
1620         stats.flist_size = stats.total_written - start_write;
1621         stats.num_files = flist->count;
1622
1623         if (verbose > 3)
1624                 output_flist(flist);
1625
1626         if (verbose > 2)
1627                 rprintf(FINFO, "send_file_list done\n");
1628
1629         if (incremental) {
1630                 add_dirs_to_tree(-1, 0, dir_flist->count - 1);
1631                 if (file_total == 1) {
1632                         /* If we're creating incremental file-lists and there
1633                          * was just 1 item in the first file-list, send 1 more
1634                          * file-list to check if this is a 1-file xfer. */
1635                         if (send_dir_ndx < 0)
1636                                 write_ndx(f, NDX_DONE);
1637                         else
1638                                 send_extra_file_list(f, 1);
1639                 }
1640         }
1641
1642         return flist;
1643 }
1644
1645 struct file_list *recv_file_list(int f)
1646 {
1647         struct file_list *flist;
1648         int dstart, flags;
1649         int64 start_read;
1650
1651         if (!first_flist)
1652                 rprintf(FLOG, "receiving file list\n");
1653         if (show_filelist_p())
1654                 start_filelist_progress("receiving file list");
1655         else if (incremental && verbose && !am_server && !first_flist)
1656                 rprintf(FCLIENT, "receiving incremental file list\n");
1657
1658         start_read = stats.total_read;
1659
1660         flist = flist_new(0, "recv_file_list");
1661
1662 #ifdef SUPPORT_HARD_LINKS
1663         if (preserve_hard_links && protocol_version < 30)
1664                 init_hard_links();
1665 #endif
1666
1667         if (incremental) {
1668                 if (flist->ndx_start == 0)
1669                         dir_flist = flist_new(FLIST_TEMP, "recv_file_list");
1670                 dstart = dir_flist->count;
1671         } else {
1672                 dir_flist = flist;
1673                 dstart = 0;
1674         }
1675
1676         while ((flags = read_byte(f)) != 0) {
1677                 struct file_struct *file;
1678
1679                 flist_expand(flist);
1680
1681                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1682                         flags |= read_byte(f) << 8;
1683                 file = recv_file_entry(flist, flags, f);
1684
1685                 if (incremental && S_ISDIR(file->mode)) {
1686                         flist_expand(dir_flist);
1687                         dir_flist->files[dir_flist->count++] = file;
1688                 }
1689
1690                 flist->files[flist->count++] = file;
1691
1692                 maybe_emit_filelist_progress(flist->count);
1693
1694                 if (verbose > 2) {
1695                         rprintf(FINFO, "recv_file_name(%s)\n",
1696                                 f_name(file, NULL));
1697                 }
1698         }
1699         file_total += flist->count;
1700
1701         if (verbose > 2)
1702                 rprintf(FINFO, "received %d names\n", flist->count);
1703
1704         if (show_filelist_p())
1705                 finish_filelist_progress(flist);
1706
1707         clean_flist(flist, relative_paths, 1);
1708
1709         if (incremental) {
1710                 qsort(dir_flist->files + dstart, dir_flist->count - dstart,
1711                       sizeof dir_flist->files[0], (int (*)())file_compare);
1712         } else if (f >= 0)
1713                 recv_uid_list(f, flist);
1714
1715         if (protocol_version < 30) {
1716                 /* Recv the io_error flag */
1717                 if (ignore_errors)
1718                         read_int(f);
1719                 else
1720                         io_error |= read_int(f);
1721         }
1722
1723         if (verbose > 3)
1724                 output_flist(flist);
1725
1726         if (list_only) {
1727                 int i;
1728                 for (i = 0; i < flist->count; i++)
1729                         list_file_entry(flist->files[i]);
1730         }
1731
1732         if (verbose > 2)
1733                 rprintf(FINFO, "recv_file_list done\n");
1734
1735         stats.flist_size += stats.total_read - start_read;
1736         stats.num_files += flist->count;
1737
1738         return flist;
1739 }
1740
1741 /* This is only used once by the receiver if the very first file-list
1742  * has exactly one item in it. */
1743 void recv_additional_file_list(int f)
1744 {
1745         struct file_list *flist;
1746         int ndx = read_ndx(f);
1747         if (ndx == NDX_DONE) {
1748                 flist_eof = 1;
1749                 change_local_filter_dir(NULL, 0, 0);
1750         } else {
1751                 ndx = NDX_FLIST_OFFSET - ndx;
1752                 if (ndx < 0 || ndx >= dir_flist->count) {
1753                         ndx = NDX_FLIST_OFFSET - ndx;
1754                         rprintf(FERROR,
1755                                 "Invalid dir index: %d (%d - %d)\n",
1756                                 ndx, NDX_FLIST_OFFSET,
1757                                 NDX_FLIST_OFFSET - dir_flist->count);
1758                         exit_cleanup(RERR_PROTOCOL);
1759                 }
1760                 flist = recv_file_list(f);
1761                 flist->parent_ndx = ndx;
1762         }
1763 }
1764
1765 /* Search for an identically-named item in the file list.  Note that the
1766  * items must agree in their directory-ness, or no match is returned. */
1767 int flist_find(struct file_list *flist, struct file_struct *f)
1768 {
1769         int low = flist->low, high = flist->high;
1770         int diff, mid, mid_up;
1771
1772         while (low <= high) {
1773                 mid = (low + high) / 2;
1774                 if (F_IS_ACTIVE(flist->files[mid]))
1775                         mid_up = mid;
1776                 else {
1777                         /* Scan for the next non-empty entry using the cached
1778                          * distance values.  If the value isn't fully up-to-
1779                          * date, update it. */
1780                         mid_up = mid + F_DEPTH(flist->files[mid]);
1781                         if (!F_IS_ACTIVE(flist->files[mid_up])) {
1782                                 do {
1783                                     mid_up += F_DEPTH(flist->files[mid_up]);
1784                                 } while (!F_IS_ACTIVE(flist->files[mid_up]));
1785                                 F_DEPTH(flist->files[mid]) = mid_up - mid;
1786                         }
1787                         if (mid_up > high) {
1788                                 /* If there's nothing left above us, set high to
1789                                  * a non-empty entry below us and continue. */
1790                                 high = mid - (int)flist->files[mid]->len32;
1791                                 if (!F_IS_ACTIVE(flist->files[high])) {
1792                                         do {
1793                                             high -= (int)flist->files[high]->len32;
1794                                         } while (!F_IS_ACTIVE(flist->files[high]));
1795                                         flist->files[mid]->len32 = mid - high;
1796                                 }
1797                                 continue;
1798                         }
1799                 }
1800                 diff = f_name_cmp(flist->files[mid_up], f);
1801                 if (diff == 0) {
1802                         if (protocol_version < 29
1803                             && S_ISDIR(flist->files[mid_up]->mode)
1804                             != S_ISDIR(f->mode))
1805                                 return -1;
1806                         return mid_up;
1807                 }
1808                 if (diff < 0)
1809                         low = mid_up + 1;
1810                 else
1811                         high = mid - 1;
1812         }
1813         return -1;
1814 }
1815
1816 /*
1817  * Free up any resources a file_struct has allocated
1818  * and clear the file.
1819  */
1820 void clear_file(struct file_struct *file)
1821 {
1822         /* The +1 zeros out the first char of the basename. */
1823         memset(file, 0, FILE_STRUCT_LEN + 1);
1824         /* In an empty entry, F_DEPTH() is an offset to the next non-empty
1825          * entry.  Likewise for len32 in the opposite direction.  We assume
1826          * that we're alone for now since flist_find() will adjust the counts
1827          * it runs into that aren't up-to-date. */
1828         file->len32 = F_DEPTH(file) = 1;
1829 }
1830
1831 /* Allocate a new file list. */
1832 struct file_list *flist_new(int flags, char *msg)
1833 {
1834         struct file_list *flist;
1835
1836         flist = new(struct file_list);
1837         if (!flist)
1838                 out_of_memory(msg);
1839
1840         memset(flist, 0, sizeof flist[0]);
1841
1842         if (!(flags & FLIST_TEMP)) {
1843                 if (first_flist) {
1844                         flist->ndx_start = first_flist->prev->ndx_start
1845                                          + first_flist->prev->count;
1846                 }
1847                 /* This is a doubly linked list with prev looping back to
1848                  * the end of the list, but the last next pointer is NULL. */
1849                 if (!first_flist)
1850                         first_flist = cur_flist = flist->prev = flist;
1851                 else {
1852                         flist->prev = first_flist->prev;
1853                         flist->prev->next = first_flist->prev = flist;
1854                 }
1855                 flist_cnt++;
1856         }
1857
1858         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0, out_of_memory, POOL_INTERN)))
1859                 out_of_memory(msg);
1860
1861         return flist;
1862 }
1863
1864 /* Free up all elements in a flist. */
1865 void flist_free(struct file_list *flist)
1866 {
1867         if (!flist->prev)
1868                 ; /* Was FLIST_TEMP dir-list. */
1869         else if (flist == flist->prev) {
1870                 first_flist = cur_flist = NULL;
1871                 file_total = 0;
1872                 flist_cnt = 0;
1873         } else {
1874                 if (flist == cur_flist)
1875                         cur_flist = flist->next;
1876                 if (flist == first_flist)
1877                         first_flist = first_flist->next;
1878                 else {
1879                         flist->prev->next = flist->next;
1880                         if (!flist->next)
1881                                 flist->next = first_flist;
1882                 }
1883                 flist->next->prev = flist->prev;
1884                 file_total -= flist->count;
1885                 flist_cnt--;
1886         }
1887
1888         pool_destroy(flist->file_pool);
1889         free(flist->files);
1890         free(flist);
1891 }
1892
1893 /*
1894  * This routine ensures we don't have any duplicate names in our file list.
1895  * duplicate names can cause corruption because of the pipelining
1896  */
1897 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1898 {
1899         char fbuf[MAXPATHLEN];
1900         int i, prev_i = 0;
1901
1902         if (!flist)
1903                 return;
1904         if (flist->count == 0) {
1905                 flist->high = -1;
1906                 return;
1907         }
1908
1909         qsort(flist->files, flist->count,
1910             sizeof flist->files[0], (int (*)())file_compare);
1911
1912         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1913                 if (F_IS_ACTIVE(flist->files[i])) {
1914                         prev_i = i;
1915                         break;
1916                 }
1917         }
1918         flist->low = prev_i;
1919         while (++i < flist->count) {
1920                 int j;
1921                 struct file_struct *file = flist->files[i];
1922
1923                 if (!F_IS_ACTIVE(file))
1924                         continue;
1925                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1926                         j = prev_i;
1927                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1928                         int save_mode = file->mode;
1929                         /* Make sure that this directory doesn't duplicate a
1930                          * non-directory earlier in the list. */
1931                         flist->high = prev_i;
1932                         file->mode = S_IFREG;
1933                         j = flist_find(flist, file);
1934                         file->mode = save_mode;
1935                 } else
1936                         j = -1;
1937                 if (j >= 0) {
1938                         struct file_struct *fp = flist->files[j];
1939                         int keep, drop;
1940                         /* If one is a dir and the other is not, we want to
1941                          * keep the dir because it might have contents in the
1942                          * list. */
1943                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1944                                 if (S_ISDIR(file->mode))
1945                                         keep = i, drop = j;
1946                                 else
1947                                         keep = j, drop = i;
1948                         } else if (protocol_version < 27)
1949                                 keep = j, drop = i;
1950                         else
1951                                 keep = i, drop = j;
1952                         if (verbose > 1 && !am_server) {
1953                                 rprintf(FINFO,
1954                                         "removing duplicate name %s from file list (%d)\n",
1955                                         f_name(file, fbuf), drop);
1956                         }
1957                         /* Make sure we don't lose track of a user-specified
1958                          * top directory. */
1959                         flist->files[keep]->flags |= flist->files[drop]->flags
1960                                                    & (FLAG_TOP_DIR|FLAG_XFER_DIR);
1961
1962                         clear_file(flist->files[drop]);
1963
1964                         if (keep == i) {
1965                                 if (flist->low == drop) {
1966                                         for (j = drop + 1;
1967                                              j < i && !F_IS_ACTIVE(flist->files[j]);
1968                                              j++) {}
1969                                         flist->low = j;
1970                                 }
1971                                 prev_i = i;
1972                         }
1973                 } else
1974                         prev_i = i;
1975         }
1976         flist->high = no_dups ? prev_i : flist->count - 1;
1977
1978         if (strip_root) {
1979                 /* We need to strip off the leading slashes for relative
1980                  * paths, but this must be done _after_ the sorting phase. */
1981                 for (i = flist->low; i <= flist->high; i++) {
1982                         struct file_struct *file = flist->files[i];
1983
1984                         if (!file->dirname)
1985                                 continue;
1986                         while (*file->dirname == '/')
1987                                 file->dirname++;
1988                         if (!*file->dirname)
1989                                 file->dirname = NULL;
1990                 }
1991         }
1992
1993         if (prune_empty_dirs && no_dups) {
1994                 int j, prev_depth = 0;
1995
1996                 prev_i = 0; /* It's OK that this isn't really true. */
1997
1998                 for (i = flist->low; i <= flist->high; i++) {
1999                         struct file_struct *fp, *file = flist->files[i];
2000
2001                         /* This temporarily abuses the F_DEPTH() value for a
2002                          * directory that is in a chain that might get pruned.
2003                          * We restore the old value if it gets a reprieve. */
2004                         if (S_ISDIR(file->mode) && F_DEPTH(file)) {
2005                                 /* Dump empty dirs when coming back down. */
2006                                 for (j = prev_depth; j >= F_DEPTH(file); j--) {
2007                                         fp = flist->files[prev_i];
2008                                         if (F_DEPTH(fp) >= 0)
2009                                                 break;
2010                                         prev_i = -F_DEPTH(fp)-1;
2011                                         clear_file(fp);
2012                                 }
2013                                 prev_depth = F_DEPTH(file);
2014                                 if (is_excluded(f_name(file, fbuf), 1,
2015                                                        ALL_FILTERS)) {
2016                                         /* Keep dirs through this dir. */
2017                                         for (j = prev_depth-1; ; j--) {
2018                                                 fp = flist->files[prev_i];
2019                                                 if (F_DEPTH(fp) >= 0)
2020                                                         break;
2021                                                 prev_i = -F_DEPTH(fp)-1;
2022                                                 F_DEPTH(fp) = j;
2023                                         }
2024                                 } else
2025                                         F_DEPTH(file) = -prev_i-1;
2026                                 prev_i = i;
2027                         } else {
2028                                 /* Keep dirs through this non-dir. */
2029                                 for (j = prev_depth; ; j--) {
2030                                         fp = flist->files[prev_i];
2031                                         if (F_DEPTH(fp) >= 0)
2032                                                 break;
2033                                         prev_i = -F_DEPTH(fp)-1;
2034                                         F_DEPTH(fp) = j;
2035                                 }
2036                         }
2037                 }
2038                 /* Dump all remaining empty dirs. */
2039                 while (1) {
2040                         struct file_struct *fp = flist->files[prev_i];
2041                         if (F_DEPTH(fp) >= 0)
2042                                 break;
2043                         prev_i = -F_DEPTH(fp)-1;
2044                         clear_file(fp);
2045                 }
2046
2047                 for (i = flist->low; i <= flist->high; i++) {
2048                         if (F_IS_ACTIVE(flist->files[i]))
2049                                 break;
2050                 }
2051                 flist->low = i;
2052                 for (i = flist->high; i >= flist->low; i--) {
2053                         if (F_IS_ACTIVE(flist->files[i]))
2054                                 break;
2055                 }
2056                 flist->high = i;
2057         }
2058 }
2059
2060 static void output_flist(struct file_list *flist)
2061 {
2062         char uidbuf[16], gidbuf[16], depthbuf[16];
2063         struct file_struct *file;
2064         const char *root, *dir, *slash, *name, *trail;
2065         const char *who = who_am_i();
2066         int i;
2067
2068         rprintf(FINFO, "[%s] flist start=%d, count=%d, low=%d, high=%d\n",
2069                 who, flist->ndx_start, flist->count, flist->low, flist->high);
2070         for (i = 0; i < flist->count; i++) {
2071                 file = flist->files[i];
2072                 if ((am_root || am_sender) && preserve_uid) {
2073                         snprintf(uidbuf, sizeof uidbuf, " uid=%ld",
2074                                  (long)F_UID(file));
2075                 } else
2076                         *uidbuf = '\0';
2077                 if (preserve_gid && F_GID(file) != GID_NONE) {
2078                         snprintf(gidbuf, sizeof gidbuf, " gid=%ld",
2079                                  (long)F_GID(file));
2080                 } else
2081                         *gidbuf = '\0';
2082                 if (!am_sender)
2083                         snprintf(depthbuf, sizeof depthbuf, "%d", F_DEPTH(file));
2084                 if (F_IS_ACTIVE(file)) {
2085                         root = am_sender ? NS(F_ROOTDIR(file)) : depthbuf;
2086                         if ((dir = file->dirname) == NULL)
2087                                 dir = slash = "";
2088                         else
2089                                 slash = "/";
2090                         name = file->basename;
2091                         trail = S_ISDIR(file->mode) ? "/" : "";
2092                 } else
2093                         root = dir = slash = name = trail = "";
2094                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
2095                         who, i, root, dir, slash, name, trail, (int)file->mode,
2096                         (double)F_LENGTH(file), uidbuf, gidbuf, file->flags);
2097         }
2098 }
2099
2100 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
2101 enum fnc_type { t_PATH, t_ITEM };
2102
2103 /* Compare the names of two file_struct entities, similar to how strcmp()
2104  * would do if it were operating on the joined strings.
2105  *
2106  * Some differences beginning with protocol_version 29: (1) directory names
2107  * are compared with an assumed trailing slash so that they compare in a
2108  * way that would cause them to sort immediately prior to any content they
2109  * may have; (2) a directory of any name compares after a non-directory of
2110  * any name at the same depth; (3) a directory with name "." compares prior
2111  * to anything else.  These changes mean that a directory and a non-dir
2112  * with the same name will not compare as equal (protocol_version >= 29).
2113  *
2114  * The dirname component can be an empty string, but the basename component
2115  * cannot (and never is in the current codebase).  The basename component
2116  * may be NULL (for a removed item), in which case it is considered to be
2117  * after any existing item. */
2118 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
2119 {
2120         int dif;
2121         const uchar *c1, *c2;
2122         enum fnc_state state1, state2;
2123         enum fnc_type type1, type2;
2124         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
2125
2126         if (!f1 || !F_IS_ACTIVE(f1)) {
2127                 if (!f2 || !F_IS_ACTIVE(f2))
2128                         return 0;
2129                 return -1;
2130         }
2131         if (!f2 || !F_IS_ACTIVE(f2))
2132                 return 1;
2133
2134         c1 = (uchar*)f1->dirname;
2135         c2 = (uchar*)f2->dirname;
2136         if (c1 == c2)
2137                 c1 = c2 = NULL;
2138         if (!c1) {
2139                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
2140                 c1 = (const uchar*)f1->basename;
2141                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
2142                         type1 = t_ITEM;
2143                         state1 = s_TRAILING;
2144                         c1 = (uchar*)"";
2145                 } else
2146                         state1 = s_BASE;
2147         } else {
2148                 type1 = t_path;
2149                 state1 = s_DIR;
2150         }
2151         if (!c2) {
2152                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
2153                 c2 = (const uchar*)f2->basename;
2154                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
2155                         type2 = t_ITEM;
2156                         state2 = s_TRAILING;
2157                         c2 = (uchar*)"";
2158                 } else
2159                         state2 = s_BASE;
2160         } else {
2161                 type2 = t_path;
2162                 state2 = s_DIR;
2163         }
2164
2165         if (type1 != type2)
2166                 return type1 == t_PATH ? 1 : -1;
2167
2168         do {
2169                 if (!*c1) {
2170                         switch (state1) {
2171                         case s_DIR:
2172                                 state1 = s_SLASH;
2173                                 c1 = (uchar*)"/";
2174                                 break;
2175                         case s_SLASH:
2176                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
2177                                 c1 = (const uchar*)f1->basename;
2178                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
2179                                         type1 = t_ITEM;
2180                                         state1 = s_TRAILING;
2181                                         c1 = (uchar*)"";
2182                                 } else
2183                                         state1 = s_BASE;
2184                                 break;
2185                         case s_BASE:
2186                                 state1 = s_TRAILING;
2187                                 if (type1 == t_PATH) {
2188                                         c1 = (uchar*)"/";
2189                                         break;
2190                                 }
2191                                 /* FALL THROUGH */
2192                         case s_TRAILING:
2193                                 type1 = t_ITEM;
2194                                 break;
2195                         }
2196                         if (*c2 && type1 != type2)
2197                                 return type1 == t_PATH ? 1 : -1;
2198                 }
2199                 if (!*c2) {
2200                         switch (state2) {
2201                         case s_DIR:
2202                                 state2 = s_SLASH;
2203                                 c2 = (uchar*)"/";
2204                                 break;
2205                         case s_SLASH:
2206                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
2207                                 c2 = (const uchar*)f2->basename;
2208                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
2209                                         type2 = t_ITEM;
2210                                         state2 = s_TRAILING;
2211                                         c2 = (uchar*)"";
2212                                 } else
2213                                         state2 = s_BASE;
2214                                 break;
2215                         case s_BASE:
2216                                 state2 = s_TRAILING;
2217                                 if (type2 == t_PATH) {
2218                                         c2 = (uchar*)"/";
2219                                         break;
2220                                 }
2221                                 /* FALL THROUGH */
2222                         case s_TRAILING:
2223                                 if (!*c1)
2224                                         return 0;
2225                                 type2 = t_ITEM;
2226                                 break;
2227                         }
2228                         if (type1 != type2)
2229                                 return type1 == t_PATH ? 1 : -1;
2230                 }
2231         } while ((dif = (int)*c1++ - (int)*c2++) == 0);
2232
2233         return dif;
2234 }
2235
2236 char *f_name_buf(void)
2237 {
2238         static char names[5][MAXPATHLEN];
2239         static unsigned int n;
2240
2241         n = (n + 1) % (sizeof names / sizeof names[0]);
2242
2243         return names[n];
2244 }
2245
2246 /* Return a copy of the full filename of a flist entry, using the indicated
2247  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
2248  * done because we checked the size when creating the file_struct entry.
2249  */
2250 char *f_name(struct file_struct *f, char *fbuf)
2251 {
2252         if (!f || !F_IS_ACTIVE(f))
2253                 return NULL;
2254
2255         if (!fbuf)
2256                 fbuf = f_name_buf();
2257
2258         if (f->dirname) {
2259                 int len = strlen(f->dirname);
2260                 memcpy(fbuf, f->dirname, len);
2261                 fbuf[len] = '/';
2262                 strlcpy(fbuf + len + 1, f->basename, MAXPATHLEN - (len + 1));
2263         } else
2264                 strlcpy(fbuf, f->basename, MAXPATHLEN);
2265
2266         return fbuf;
2267 }
2268
2269 /* Do a non-recursive scan of the named directory, possibly ignoring all
2270  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
2271  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
2272  * buffer (the functions we call will append names onto the end, but the old
2273  * dir value will be restored on exit). */
2274 struct file_list *get_dirlist(char *dirname, int dlen, int ignore_filter_rules)
2275 {
2276         struct file_list *dirlist;
2277         char dirbuf[MAXPATHLEN];
2278         int save_recurse = recurse;
2279         int save_xfer_dirs = xfer_dirs;
2280
2281         if (dlen < 0) {
2282                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
2283                 if (dlen >= MAXPATHLEN)
2284                         return NULL;
2285                 dirname = dirbuf;
2286         }
2287
2288         dirlist = flist_new(FLIST_TEMP, "get_dirlist");
2289
2290         recurse = 0;
2291         xfer_dirs = 1;
2292         send_directory(ignore_filter_rules ? -2 : -1, dirlist, -1, dirname, dlen, 0);
2293         xfer_dirs = save_xfer_dirs;
2294         recurse = save_recurse;
2295         if (do_progress)
2296                 flist_count_offset += dirlist->count;
2297
2298         clean_flist(dirlist, 0, 0);
2299
2300         if (verbose > 3)
2301                 output_flist(dirlist);
2302
2303         return dirlist;
2304 }