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