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