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