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