c17a5620d704ac70c9e7e2ec3fbfda92d7e3132a
[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-2020 Wayne Davison
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with this program; if not, visit the http://fsf.org website.
21  */
22
23 #include "rsync.h"
24 #include "ifuncs.h"
25 #include "rounding.h"
26 #include "inums.h"
27 #include "io.h"
28
29 extern int am_root;
30 extern int am_server;
31 extern int am_daemon;
32 extern int am_sender;
33 extern int am_generator;
34 extern int inc_recurse;
35 extern int always_checksum;
36 extern int checksum_type;
37 extern int module_id;
38 extern int ignore_errors;
39 extern int numeric_ids;
40 extern int quiet;
41 extern int recurse;
42 extern int use_qsort;
43 extern int xfer_dirs;
44 extern int filesfrom_fd;
45 extern int one_file_system;
46 extern int copy_dirlinks;
47 extern int preserve_uid;
48 extern int preserve_gid;
49 extern int preserve_acls;
50 extern int preserve_xattrs;
51 extern int preserve_links;
52 extern int preserve_hard_links;
53 extern int preserve_devices;
54 extern int preserve_specials;
55 extern int delete_during;
56 extern int missing_args;
57 extern int eol_nulls;
58 extern int atimes_ndx;
59 extern int relative_paths;
60 extern int implied_dirs;
61 extern int ignore_perishable;
62 extern int non_perishable_cnt;
63 extern int prune_empty_dirs;
64 extern int copy_links;
65 extern int copy_unsafe_links;
66 extern int protocol_version;
67 extern int sanitize_paths;
68 extern int munge_symlinks;
69 extern int use_safe_inc_flist;
70 extern int need_unsorted_flist;
71 extern int sender_symlink_iconv;
72 extern int output_needs_newline;
73 extern int sender_keeps_checksum;
74 extern int unsort_ndx;
75 extern uid_t our_uid;
76 extern struct stats stats;
77 extern char *filesfrom_host;
78 extern char *usermap, *groupmap;
79
80 extern char curr_dir[MAXPATHLEN];
81
82 extern struct chmod_mode_struct *chmod_modes;
83
84 extern filter_rule_list filter_list;
85 extern filter_rule_list daemon_filter_list;
86
87 #ifdef ICONV_OPTION
88 extern int filesfrom_convert;
89 extern iconv_t ic_send, ic_recv;
90 #endif
91
92 #define PTR_SIZE (sizeof (struct file_struct *))
93
94 int io_error;
95 int flist_csum_len;
96 dev_t filesystem_dev; /* used to implement -x */
97
98 struct file_list *cur_flist, *first_flist, *dir_flist;
99 int send_dir_ndx = -1, send_dir_depth = -1;
100 int flist_cnt = 0; /* how many (non-tmp) file list objects exist */
101 int file_total = 0; /* total of all active items over all file-lists */
102 int file_old_total = 0; /* total of active items that will soon be gone */
103 int flist_eof = 0; /* all the file-lists are now known */
104 int xfer_flags_as_varint = 0;
105
106 #define NORMAL_NAME 0
107 #define SLASH_ENDING_NAME 1
108 #define DOTDIR_NAME 2
109 #define MISSING_NAME 3
110
111 /* Starting from protocol version 26, we always use 64-bit ino_t and dev_t
112  * internally, even if this platform does not allow files to have 64-bit inums.
113  * The only exception is if we're on a platform with no 64-bit type at all.
114  *
115  * Because we use read_longint() to get these off the wire, if you transfer
116  * devices or (for protocols < 30) hardlinks with dev or inum > 2**32 to a
117  * machine with no 64-bit types then you will get an overflow error.
118  *
119  * Note that if you transfer devices from a 64-bit-devt machine (say, Solaris)
120  * to a 32-bit-devt machine (say, Linux-2.2/x86) then the device numbers will
121  * be truncated.  But it's a kind of silly thing to do anyhow. */
122
123 /* The tmp_* vars are used as a cache area by make_file() to store data
124  * that the sender doesn't need to remember in its file list.  The data
125  * will survive just long enough to be used by send_file_entry(). */
126 static dev_t tmp_rdev;
127 #ifdef SUPPORT_HARD_LINKS
128 static int64 tmp_dev = -1, tmp_ino;
129 #endif
130 static char tmp_sum[MAX_DIGEST_LEN];
131
132 static char empty_sum[MAX_DIGEST_LEN];
133 static int flist_count_offset; /* for --delete --progress */
134 static int show_filelist_progress;
135
136 static void flist_sort_and_clean(struct file_list *flist, int strip_root);
137 static void output_flist(struct file_list *flist);
138
139 void init_flist(void)
140 {
141         if (DEBUG_GTE(FLIST, 4)) {
142                 rprintf(FINFO, "FILE_STRUCT_LEN=%d, EXTRA_LEN=%d\n",
143                         (int)FILE_STRUCT_LEN, (int)EXTRA_LEN);
144         }
145         flist_csum_len = csum_len_for_type(checksum_type, 1);
146
147         show_filelist_progress = INFO_GTE(FLIST, 1) && xfer_dirs && !am_server && !inc_recurse;
148 }
149
150 static void start_filelist_progress(char *kind)
151 {
152         if (quiet)
153                 return;
154         rprintf(FCLIENT, "%s ... ", kind);
155         output_needs_newline = 1;
156         rflush(FINFO);
157 }
158
159 static void emit_filelist_progress(int count)
160 {
161         if (quiet)
162                 return;
163         if (output_needs_newline == 2) /* avoid a newline in the middle of this filelist-progress output */
164                 output_needs_newline = 0;
165         rprintf(FCLIENT, " %d files...\r", count);
166         output_needs_newline = 2;
167 }
168
169 static void maybe_emit_filelist_progress(int count)
170 {
171         if (INFO_GTE(FLIST, 2) && show_filelist_progress && (count % 100) == 0)
172                 emit_filelist_progress(count);
173 }
174
175 static void finish_filelist_progress(const struct file_list *flist)
176 {
177         output_needs_newline = 0;
178         if (INFO_GTE(FLIST, 2)) {
179                 /* This overwrites the progress line */
180                 rprintf(FINFO, "%d file%sto consider\n",
181                         flist->used, flist->used == 1 ? " " : "s ");
182         } else {
183                 rprintf(FINFO, "done\n");
184         }
185 }
186
187 void show_flist_stats(void)
188 {
189         /* Nothing yet */
190 }
191
192 /* Stat either a symlink or its referent, depending on the settings of
193  * copy_links, copy_unsafe_links, etc.  Returns -1 on error, 0 on success.
194  *
195  * If path is the name of a symlink, then the linkbuf buffer (which must hold
196  * MAXPATHLEN chars) will be set to the symlink's target string.
197  *
198  * The stat structure pointed to by stp will contain information about the
199  * link or the referent as appropriate, if they exist. */
200 static int readlink_stat(const char *path, STRUCT_STAT *stp, char *linkbuf)
201 {
202 #ifdef SUPPORT_LINKS
203         if (link_stat(path, stp, copy_dirlinks) < 0)
204                 return -1;
205         if (S_ISLNK(stp->st_mode)) {
206                 int llen = do_readlink(path, linkbuf, MAXPATHLEN - 1);
207                 if (llen < 0)
208                         return -1;
209                 linkbuf[llen] = '\0';
210                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
211                         if (INFO_GTE(SYMSAFE, 1)) {
212                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
213                                         path, linkbuf);
214                         }
215                         return x_stat(path, stp, NULL);
216                 }
217                 if (munge_symlinks && am_sender && llen > SYMLINK_PREFIX_LEN
218                  && strncmp(linkbuf, SYMLINK_PREFIX, SYMLINK_PREFIX_LEN) == 0) {
219                         memmove(linkbuf, linkbuf + SYMLINK_PREFIX_LEN,
220                                 llen - SYMLINK_PREFIX_LEN + 1);
221                 }
222         }
223         return 0;
224 #else
225         return x_stat(path, stp, NULL);
226 #endif
227 }
228
229 int link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
230 {
231 #ifdef SUPPORT_LINKS
232         if (copy_links)
233                 return x_stat(path, stp, NULL);
234         if (x_lstat(path, stp, NULL) < 0)
235                 return -1;
236         if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
237                 STRUCT_STAT st;
238                 if (x_stat(path, &st, NULL) == 0 && S_ISDIR(st.st_mode))
239                         *stp = st;
240         }
241         return 0;
242 #else
243         return x_stat(path, stp, NULL);
244 #endif
245 }
246
247 static inline int path_is_daemon_excluded(char *path, int ignore_filename)
248 {
249         if (daemon_filter_list.head) {
250                 char *slash = path;
251
252                 while ((slash = strchr(slash+1, '/')) != NULL) {
253                         int ret;
254                         *slash = '\0';
255                         ret = check_filter(&daemon_filter_list, FLOG, path, 1);
256                         *slash = '/';
257                         if (ret < 0) {
258                                 errno = ENOENT;
259                                 return 1;
260                         }
261                 }
262
263                 if (!ignore_filename
264                  && check_filter(&daemon_filter_list, FLOG, path, 1) < 0) {
265                         errno = ENOENT;
266                         return 1;
267                 }
268         }
269
270         return 0;
271 }
272
273 static inline int is_excluded(const char *fname, int is_dir, int filter_level)
274 {
275         return name_is_excluded(fname, is_dir ? NAME_IS_DIR : NAME_IS_FILE, filter_level);
276 }
277
278 static void send_directory(int f, struct file_list *flist,
279                            char *fbuf, int len, int flags);
280
281 static const char *pathname, *orig_dir;
282 static int pathname_len;
283
284 /* Make sure flist can hold at least flist->used + extra entries. */
285 static void flist_expand(struct file_list *flist, int extra)
286 {
287         struct file_struct **new_ptr;
288
289         if (flist->used + extra <= flist->malloced)
290                 return;
291
292         if (flist->malloced < FLIST_START)
293                 flist->malloced = FLIST_START;
294         else if (flist->malloced >= FLIST_LINEAR)
295                 flist->malloced += FLIST_LINEAR;
296         else
297                 flist->malloced *= 2;
298
299         /* In case count jumped or we are starting the list
300          * with a known size just set it. */
301         if (flist->malloced < flist->used + extra)
302                 flist->malloced = flist->used + extra;
303
304         new_ptr = realloc_array(flist->files, struct file_struct *, flist->malloced);
305
306         if (DEBUG_GTE(FLIST, 1) && flist->malloced != FLIST_START) {
307                 rprintf(FCLIENT, "[%s] expand file_list pointer array to %s bytes, did%s move\n",
308                     who_am_i(),
309                     big_num(sizeof flist->files[0] * flist->malloced),
310                     (new_ptr == flist->files) ? " not" : "");
311         }
312
313         flist->files = new_ptr;
314 }
315
316 static void flist_done_allocating(struct file_list *flist)
317 {
318         void *ptr = pool_boundary(flist->file_pool, 8*1024);
319         if (flist->pool_boundary == ptr)
320                 flist->pool_boundary = NULL; /* list didn't use any pool memory */
321         else
322                 flist->pool_boundary = ptr;
323 }
324
325 /* Call this with EITHER (1) "file, NULL, 0" to chdir() to the file's
326  * F_PATHNAME(), or (2) "NULL, dir, dirlen" to chdir() to the supplied dir,
327  * with dir == NULL taken to be the starting directory, and dirlen < 0
328  * indicating that strdup(dir) should be called and then the -dirlen length
329  * value checked to ensure that it is not daemon-excluded. */
330 int change_pathname(struct file_struct *file, const char *dir, int dirlen)
331 {
332         if (dirlen < 0) {
333                 char *cpy = strdup(dir);
334                 if (*cpy != '/')
335                         change_dir(orig_dir, CD_SKIP_CHDIR);
336                 if (path_is_daemon_excluded(cpy, 0))
337                         goto chdir_error;
338                 dir = cpy;
339                 dirlen = -dirlen;
340         } else {
341                 if (file) {
342                         if (pathname == F_PATHNAME(file))
343                                 return 1;
344                         dir = F_PATHNAME(file);
345                         if (dir)
346                                 dirlen = strlen(dir);
347                 } else if (pathname == dir)
348                         return 1;
349                 if (dir && *dir != '/')
350                         change_dir(orig_dir, CD_SKIP_CHDIR);
351         }
352
353         pathname = dir;
354         pathname_len = dirlen;
355
356         if (!dir)
357                 dir = orig_dir;
358
359         if (!change_dir(dir, CD_NORMAL)) {
360           chdir_error:
361                 io_error |= IOERR_GENERAL;
362                 rsyserr(FERROR_XFER, errno, "change_dir %s failed", full_fname(dir));
363                 if (dir != orig_dir)
364                         change_dir(orig_dir, CD_NORMAL);
365                 pathname = NULL;
366                 pathname_len = 0;
367                 return 0;
368         }
369
370         return 1;
371 }
372
373 static void send_file_entry(int f, const char *fname, struct file_struct *file,
374 #ifdef SUPPORT_LINKS
375                             const char *symlink_name, int symlink_len,
376 #endif
377                             int ndx, int first_ndx)
378 {
379         static time_t modtime, atime;
380         static mode_t mode;
381 #ifdef SUPPORT_HARD_LINKS
382         static int64 dev;
383 #endif
384         static dev_t rdev;
385         static uint32 rdev_major;
386         static uid_t uid;
387         static gid_t gid;
388         static const char *user_name, *group_name;
389         static char lastname[MAXPATHLEN];
390 #ifdef SUPPORT_HARD_LINKS
391         int first_hlink_ndx = -1;
392 #endif
393         int l1, l2;
394         int xflags;
395
396         /* Initialize starting value of xflags and adjust counts. */
397         if (S_ISREG(file->mode))
398                 xflags = 0;
399         else if (S_ISDIR(file->mode)) {
400                 stats.num_dirs++;
401                 if (protocol_version >= 30) {
402                         if (file->flags & FLAG_CONTENT_DIR)
403                                 xflags = file->flags & FLAG_TOP_DIR;
404                         else if (file->flags & FLAG_IMPLIED_DIR)
405                                 xflags = XMIT_TOP_DIR | XMIT_NO_CONTENT_DIR;
406                         else
407                                 xflags = XMIT_NO_CONTENT_DIR;
408                 } else
409                         xflags = file->flags & FLAG_TOP_DIR; /* FLAG_TOP_DIR == XMIT_TOP_DIR */
410         } else {
411                 if (S_ISLNK(file->mode))
412                         stats.num_symlinks++;
413                 else if (IS_DEVICE(file->mode))
414                         stats.num_devices++;
415                 else if (IS_SPECIAL(file->mode))
416                         stats.num_specials++;
417                 xflags = 0;
418         }
419
420         if (file->mode == mode)
421                 xflags |= XMIT_SAME_MODE;
422         else
423                 mode = file->mode;
424
425         if (preserve_devices && IS_DEVICE(mode)) {
426                 if (protocol_version < 28) {
427                         if (tmp_rdev == rdev)
428                                 xflags |= XMIT_SAME_RDEV_pre28;
429                         else
430                                 rdev = tmp_rdev;
431                 } else {
432                         rdev = tmp_rdev;
433                         if ((uint32)major(rdev) == rdev_major)
434                                 xflags |= XMIT_SAME_RDEV_MAJOR;
435                         else
436                                 rdev_major = major(rdev);
437                         if (protocol_version < 30 && (uint32)minor(rdev) <= 0xFFu)
438                                 xflags |= XMIT_RDEV_MINOR_8_pre30;
439                 }
440         } else if (preserve_specials && IS_SPECIAL(mode) && protocol_version < 31) {
441                 /* Special files don't need an rdev number, so just make
442                  * the historical transmission of the value efficient. */
443                 if (protocol_version < 28)
444                         xflags |= XMIT_SAME_RDEV_pre28;
445                 else {
446                         rdev = MAKEDEV(major(rdev), 0);
447                         xflags |= XMIT_SAME_RDEV_MAJOR;
448                         if (protocol_version < 30)
449                                 xflags |= XMIT_RDEV_MINOR_8_pre30;
450                 }
451         } else if (protocol_version < 28)
452                 rdev = MAKEDEV(0, 0);
453         if (!preserve_uid || ((uid_t)F_OWNER(file) == uid && *lastname))
454                 xflags |= XMIT_SAME_UID;
455         else {
456                 uid = F_OWNER(file);
457                 if (!numeric_ids) {
458                         user_name = add_uid(uid);
459                         if (inc_recurse && user_name)
460                                 xflags |= XMIT_USER_NAME_FOLLOWS;
461                 }
462         }
463         if (!preserve_gid || ((gid_t)F_GROUP(file) == gid && *lastname))
464                 xflags |= XMIT_SAME_GID;
465         else {
466                 gid = F_GROUP(file);
467                 if (!numeric_ids) {
468                         group_name = add_gid(gid);
469                         if (inc_recurse && group_name)
470                                 xflags |= XMIT_GROUP_NAME_FOLLOWS;
471                 }
472         }
473         if (file->modtime == modtime)
474                 xflags |= XMIT_SAME_TIME;
475         else
476                 modtime = file->modtime;
477         if (NSEC_BUMP(file) && protocol_version >= 31)
478                 xflags |= XMIT_MOD_NSEC;
479         if (atimes_ndx && !S_ISDIR(mode)) {
480                 if (F_ATIME(file) == atime)
481                         xflags |= XMIT_SAME_ATIME;
482                 else
483                         atime = F_ATIME(file);
484         }
485
486 #ifdef SUPPORT_HARD_LINKS
487         if (tmp_dev != -1) {
488                 if (protocol_version >= 30) {
489                         struct ht_int64_node *np = idev_find(tmp_dev, tmp_ino);
490                         first_hlink_ndx = (int32)(long)np->data; /* is -1 when new */
491                         if (first_hlink_ndx < 0) {
492                                 np->data = (void*)(long)(first_ndx + ndx);
493                                 xflags |= XMIT_HLINK_FIRST;
494                         }
495                         if (DEBUG_GTE(HLINK, 1)) {
496                                 if (first_hlink_ndx >= 0) {
497                                         rprintf(FINFO, "[%s] #%d hard-links #%d (%sabbrev)\n",
498                                                 who_am_i(), first_ndx + ndx, first_hlink_ndx,
499                                                 first_hlink_ndx >= first_ndx ? "" : "un");
500                                 } else if (DEBUG_GTE(HLINK, 3)) {
501                                         rprintf(FINFO, "[%s] dev:inode for #%d is %s:%s\n",
502                                                 who_am_i(), first_ndx + ndx,
503                                                 big_num(tmp_dev), big_num(tmp_ino));
504                                 }
505                         }
506                 } else {
507                         if (tmp_dev == dev) {
508                                 if (protocol_version >= 28)
509                                         xflags |= XMIT_SAME_DEV_pre30;
510                         } else
511                                 dev = tmp_dev;
512                 }
513                 xflags |= XMIT_HLINKED;
514         }
515 #endif
516
517         for (l1 = 0;
518             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
519             l1++) {}
520         l2 = strlen(fname+l1);
521
522         if (l1 > 0)
523                 xflags |= XMIT_SAME_NAME;
524         if (l2 > 255)
525                 xflags |= XMIT_LONG_NAME;
526
527         /* We must avoid sending a flag value of 0 (or an initial byte of
528          * 0 for the older xflags protocol) or it will signal the end of
529          * the list.  Note that the use of XMIT_TOP_DIR on a non-dir has
530          * no meaning, so it's a harmless way to add a bit to the first
531          * flag byte. */
532         if (xfer_flags_as_varint)
533                 write_varint(f, xflags ? xflags : XMIT_EXTENDED_FLAGS);
534         else if (protocol_version >= 28) {
535                 if (!xflags && !S_ISDIR(mode))
536                         xflags |= XMIT_TOP_DIR;
537                 if ((xflags & 0xFF00) || !xflags) {
538                         xflags |= XMIT_EXTENDED_FLAGS;
539                         write_shortint(f, xflags);
540                 } else
541                         write_byte(f, xflags);
542         } else {
543                 if (!(xflags & 0xFF))
544                         xflags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
545                 write_byte(f, xflags);
546         }
547         if (xflags & XMIT_SAME_NAME)
548                 write_byte(f, l1);
549         if (xflags & XMIT_LONG_NAME)
550                 write_varint30(f, l2);
551         else
552                 write_byte(f, l2);
553         write_buf(f, fname + l1, l2);
554
555 #ifdef SUPPORT_HARD_LINKS
556         if (first_hlink_ndx >= 0) {
557                 write_varint(f, first_hlink_ndx);
558                 if (first_hlink_ndx >= first_ndx)
559                         goto the_end;
560         }
561 #endif
562
563         write_varlong30(f, F_LENGTH(file), 3);
564         if (!(xflags & XMIT_SAME_TIME)) {
565                 if (protocol_version >= 30)
566                         write_varlong(f, modtime, 4);
567                 else
568                         write_int(f, modtime);
569         }
570         if (xflags & XMIT_MOD_NSEC)
571                 write_varint(f, F_MOD_NSEC(file));
572         if (!(xflags & XMIT_SAME_MODE))
573                 write_int(f, to_wire_mode(mode));
574         if (atimes_ndx && !S_ISDIR(mode) && !(xflags & XMIT_SAME_ATIME))
575                 write_varlong(f, atime, 4);
576         if (preserve_uid && !(xflags & XMIT_SAME_UID)) {
577                 if (protocol_version < 30)
578                         write_int(f, uid);
579                 else {
580                         write_varint(f, uid);
581                         if (xflags & XMIT_USER_NAME_FOLLOWS) {
582                                 int len = strlen(user_name);
583                                 write_byte(f, len);
584                                 write_buf(f, user_name, len);
585                         }
586                 }
587         }
588         if (preserve_gid && !(xflags & XMIT_SAME_GID)) {
589                 if (protocol_version < 30)
590                         write_int(f, gid);
591                 else {
592                         write_varint(f, gid);
593                         if (xflags & XMIT_GROUP_NAME_FOLLOWS) {
594                                 int len = strlen(group_name);
595                                 write_byte(f, len);
596                                 write_buf(f, group_name, len);
597                         }
598                 }
599         }
600         if ((preserve_devices && IS_DEVICE(mode))
601          || (preserve_specials && IS_SPECIAL(mode) && protocol_version < 31)) {
602                 if (protocol_version < 28) {
603                         if (!(xflags & XMIT_SAME_RDEV_pre28))
604                                 write_int(f, (int)rdev);
605                 } else {
606                         if (!(xflags & XMIT_SAME_RDEV_MAJOR))
607                                 write_varint30(f, major(rdev));
608                         if (protocol_version >= 30)
609                                 write_varint(f, minor(rdev));
610                         else if (xflags & XMIT_RDEV_MINOR_8_pre30)
611                                 write_byte(f, minor(rdev));
612                         else
613                                 write_int(f, minor(rdev));
614                 }
615         }
616
617 #ifdef SUPPORT_LINKS
618         if (symlink_len) {
619                 write_varint30(f, symlink_len);
620                 write_buf(f, symlink_name, symlink_len);
621         }
622 #endif
623
624 #ifdef SUPPORT_HARD_LINKS
625         if (tmp_dev != -1 && protocol_version < 30) {
626                 /* Older protocols expect the dev number to be transmitted
627                  * 1-incremented so that it is never zero. */
628                 if (protocol_version < 26) {
629                         /* 32-bit dev_t and ino_t */
630                         write_int(f, (int32)(dev+1));
631                         write_int(f, (int32)tmp_ino);
632                 } else {
633                         /* 64-bit dev_t and ino_t */
634                         if (!(xflags & XMIT_SAME_DEV_pre30))
635                                 write_longint(f, dev+1);
636                         write_longint(f, tmp_ino);
637                 }
638         }
639 #endif
640
641         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
642                 const char *sum;
643                 if (S_ISREG(mode))
644                         sum = tmp_sum;
645                 else {
646                         /* Prior to 28, we sent a useless set of nulls. */
647                         sum = empty_sum;
648                 }
649                 write_buf(f, sum, flist_csum_len);
650         }
651
652 #ifdef SUPPORT_HARD_LINKS
653   the_end:
654 #endif
655         strlcpy(lastname, fname, MAXPATHLEN);
656
657         if (S_ISREG(mode) || S_ISLNK(mode))
658                 stats.total_size += F_LENGTH(file);
659 }
660
661 static struct file_struct *recv_file_entry(int f, struct file_list *flist, int xflags)
662 {
663         static int64 modtime, atime;
664         static mode_t mode;
665 #ifdef SUPPORT_HARD_LINKS
666         static int64 dev;
667 #endif
668         static dev_t rdev;
669         static uint32 rdev_major;
670         static uid_t uid;
671         static gid_t gid;
672         static uint16 gid_flags;
673         static char lastname[MAXPATHLEN], *lastdir;
674         static int lastdir_depth, lastdir_len = -1;
675         static unsigned int del_hier_name_len = 0;
676         static int in_del_hier = 0;
677         char thisname[MAXPATHLEN];
678         unsigned int l1 = 0, l2 = 0;
679         int alloc_len, basename_len, linkname_len;
680         int extra_len = file_extra_cnt * EXTRA_LEN;
681         int first_hlink_ndx = -1;
682         int64 file_length;
683         uint32 modtime_nsec;
684         const char *basename;
685         struct file_struct *file;
686         alloc_pool_t *pool;
687         char *bp;
688
689         if (xflags & XMIT_SAME_NAME)
690                 l1 = read_byte(f);
691
692         if (xflags & XMIT_LONG_NAME)
693                 l2 = read_varint30(f);
694         else
695                 l2 = read_byte(f);
696
697         if (l2 >= MAXPATHLEN - l1) {
698                 rprintf(FERROR,
699                         "overflow: xflags=0x%x l1=%d l2=%d lastname=%s [%s]\n",
700                         xflags, l1, l2, lastname, who_am_i());
701                 overflow_exit("recv_file_entry");
702         }
703
704         strlcpy(thisname, lastname, l1 + 1);
705         read_sbuf(f, &thisname[l1], l2);
706         thisname[l1 + l2] = 0;
707
708         /* Abuse basename_len for a moment... */
709         basename_len = strlcpy(lastname, thisname, MAXPATHLEN);
710
711 #ifdef ICONV_OPTION
712         if (ic_recv != (iconv_t)-1) {
713                 xbuf outbuf, inbuf;
714
715                 INIT_CONST_XBUF(outbuf, thisname);
716                 INIT_XBUF(inbuf, lastname, basename_len, (size_t)-1);
717
718                 if (iconvbufs(ic_recv, &inbuf, &outbuf, ICB_INIT) < 0) {
719                         io_error |= IOERR_GENERAL;
720                         rprintf(FERROR_UTF8,
721                             "[%s] cannot convert filename: %s (%s)\n",
722                             who_am_i(), lastname, strerror(errno));
723                         outbuf.len = 0;
724                 }
725                 thisname[outbuf.len] = '\0';
726         }
727 #endif
728
729         if (*thisname
730          && (clean_fname(thisname, CFN_REFUSE_DOT_DOT_DIRS) < 0 || (!relative_paths && *thisname == '/'))) {
731                 rprintf(FERROR, "ABORTING due to unsafe pathname from sender: %s\n", thisname);
732                 exit_cleanup(RERR_PROTOCOL);
733         }
734
735         if (sanitize_paths)
736                 sanitize_path(thisname, thisname, "", 0, SP_DEFAULT);
737
738         if ((basename = strrchr(thisname, '/')) != NULL) {
739                 int len = basename++ - thisname;
740                 if (len != lastdir_len || memcmp(thisname, lastdir, len) != 0) {
741                         lastdir = new_array(char, len + 1);
742                         memcpy(lastdir, thisname, len);
743                         lastdir[len] = '\0';
744                         lastdir_len = len;
745                         lastdir_depth = count_dir_elements(lastdir);
746                 }
747         } else
748                 basename = thisname;
749         basename_len = strlen(basename) + 1; /* count the '\0' */
750
751 #ifdef SUPPORT_HARD_LINKS
752         if (protocol_version >= 30
753          && BITS_SETnUNSET(xflags, XMIT_HLINKED, XMIT_HLINK_FIRST)) {
754                 first_hlink_ndx = read_varint(f);
755                 if (first_hlink_ndx < 0 || first_hlink_ndx >= flist->ndx_start + flist->used) {
756                         rprintf(FERROR,
757                                 "hard-link reference out of range: %d (%d)\n",
758                                 first_hlink_ndx, flist->ndx_start + flist->used);
759                         exit_cleanup(RERR_PROTOCOL);
760                 }
761                 if (DEBUG_GTE(HLINK, 1)) {
762                         rprintf(FINFO, "[%s] #%d hard-links #%d (%sabbrev)\n",
763                                 who_am_i(), flist->used+flist->ndx_start, first_hlink_ndx,
764                                 first_hlink_ndx >= flist->ndx_start ? "" : "un");
765                 }
766                 if (first_hlink_ndx >= flist->ndx_start) {
767                         struct file_struct *first = flist->files[first_hlink_ndx - flist->ndx_start];
768                         file_length = F_LENGTH(first);
769                         modtime = first->modtime;
770                         modtime_nsec = F_MOD_NSEC_or_0(first);
771                         mode = first->mode;
772                         if (atimes_ndx && !S_ISDIR(mode))
773                                 atime = F_ATIME(first);
774                         if (preserve_uid)
775                                 uid = F_OWNER(first);
776                         if (preserve_gid)
777                                 gid = F_GROUP(first);
778                         if (preserve_devices && IS_DEVICE(mode)) {
779                                 uint32 *devp = F_RDEV_P(first);
780                                 rdev = MAKEDEV(DEV_MAJOR(devp), DEV_MINOR(devp));
781                                 extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
782                         }
783                         if (preserve_links && S_ISLNK(mode))
784                                 linkname_len = strlen(F_SYMLINK(first)) + 1;
785                         else
786                                 linkname_len = 0;
787                         goto create_object;
788                 }
789         }
790 #endif
791
792         file_length = read_varlong30(f, 3);
793         if (!(xflags & XMIT_SAME_TIME)) {
794                 if (protocol_version >= 30) {
795                         modtime = read_varlong(f, 4);
796 #if SIZEOF_TIME_T < SIZEOF_INT64
797                         if (!am_generator && (int64)(time_t)modtime != modtime) {
798                                 rprintf(FERROR_XFER,
799                                     "Time value of %s truncated on receiver.\n",
800                                     lastname);
801                         }
802 #endif
803                 } else
804                         modtime = read_int(f);
805         }
806         if (xflags & XMIT_MOD_NSEC)
807                 modtime_nsec = read_varint(f);
808         else
809                 modtime_nsec = 0;
810         if (!(xflags & XMIT_SAME_MODE))
811                 mode = from_wire_mode(read_int(f));
812         if (atimes_ndx && !S_ISDIR(mode) && !(xflags & XMIT_SAME_ATIME)) {
813                 atime = read_varlong(f, 4);
814 #if SIZEOF_TIME_T < SIZEOF_INT64
815                 if (!am_generator && (int64)(time_t)atime != atime) {
816                         rprintf(FERROR_XFER,
817                                 "Access time value of %s truncated on receiver.\n",
818                                 lastname);
819                 }
820 #endif
821         }
822
823         if (chmod_modes && !S_ISLNK(mode) && mode)
824                 mode = tweak_mode(mode, chmod_modes);
825
826         if (preserve_uid && !(xflags & XMIT_SAME_UID)) {
827                 if (protocol_version < 30)
828                         uid = (uid_t)read_int(f);
829                 else {
830                         uid = (uid_t)read_varint(f);
831                         if (xflags & XMIT_USER_NAME_FOLLOWS)
832                                 uid = recv_user_name(f, uid);
833                         else if (inc_recurse && am_root && (!numeric_ids || usermap))
834                                 uid = match_uid(uid);
835                 }
836         }
837         if (preserve_gid && !(xflags & XMIT_SAME_GID)) {
838                 if (protocol_version < 30)
839                         gid = (gid_t)read_int(f);
840                 else {
841                         gid = (gid_t)read_varint(f);
842                         gid_flags = 0;
843                         if (xflags & XMIT_GROUP_NAME_FOLLOWS)
844                                 gid = recv_group_name(f, gid, &gid_flags);
845                         else if (inc_recurse && (!am_root || !numeric_ids || groupmap))
846                                 gid = match_gid(gid, &gid_flags);
847                 }
848         }
849
850         if ((preserve_devices && IS_DEVICE(mode))
851          || (preserve_specials && IS_SPECIAL(mode) && protocol_version < 31)) {
852                 if (protocol_version < 28) {
853                         if (!(xflags & XMIT_SAME_RDEV_pre28))
854                                 rdev = (dev_t)read_int(f);
855                 } else {
856                         uint32 rdev_minor;
857                         if (!(xflags & XMIT_SAME_RDEV_MAJOR))
858                                 rdev_major = read_varint30(f);
859                         if (protocol_version >= 30)
860                                 rdev_minor = read_varint(f);
861                         else if (xflags & XMIT_RDEV_MINOR_8_pre30)
862                                 rdev_minor = read_byte(f);
863                         else
864                                 rdev_minor = read_int(f);
865                         rdev = MAKEDEV(rdev_major, rdev_minor);
866                 }
867                 if (IS_DEVICE(mode))
868                         extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
869                 file_length = 0;
870         } else if (protocol_version < 28)
871                 rdev = MAKEDEV(0, 0);
872
873 #ifdef SUPPORT_LINKS
874         if (preserve_links && S_ISLNK(mode)) {
875                 linkname_len = read_varint30(f) + 1; /* count the '\0' */
876                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
877                         rprintf(FERROR, "overflow: linkname_len=%d\n",
878                                 linkname_len - 1);
879                         overflow_exit("recv_file_entry");
880                 }
881 #ifdef ICONV_OPTION
882                 /* We don't know how much extra room we need to convert
883                  * the as-yet-unread symlink data, so let's hope that a
884                  * double-size buffer is plenty. */
885                 if (sender_symlink_iconv)
886                         linkname_len *= 2;
887 #endif
888                 if (munge_symlinks)
889                         linkname_len += SYMLINK_PREFIX_LEN;
890         }
891         else
892 #endif
893                 linkname_len = 0;
894
895 #ifdef SUPPORT_HARD_LINKS
896   create_object:
897         if (preserve_hard_links) {
898                 if (protocol_version < 28 && S_ISREG(mode))
899                         xflags |= XMIT_HLINKED;
900                 if (xflags & XMIT_HLINKED)
901                         extra_len += (inc_recurse+1) * EXTRA_LEN;
902         }
903 #endif
904
905 #ifdef SUPPORT_ACLS
906         /* Directories need an extra int32 for the default ACL. */
907         if (preserve_acls && S_ISDIR(mode))
908                 extra_len += EXTRA_LEN;
909 #endif
910
911         if (always_checksum && S_ISREG(mode))
912                 extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
913
914 #if SIZEOF_INT64 >= 8
915         if (file_length > 0xFFFFFFFFu && S_ISREG(mode))
916                 extra_len += EXTRA_LEN;
917 #endif
918 #ifdef CAN_SET_NSEC
919         if (modtime_nsec)
920                 extra_len += EXTRA_LEN;
921 #endif
922         if (file_length < 0) {
923                 rprintf(FERROR, "Offset underflow: file-length is negative\n");
924                 exit_cleanup(RERR_UNSUPPORTED);
925         }
926
927         if (inc_recurse && S_ISDIR(mode)) {
928                 if (one_file_system) {
929                         /* Room to save the dir's device for -x */
930                         extra_len += DEV_EXTRA_CNT * EXTRA_LEN;
931                 }
932                 pool = dir_flist->file_pool;
933         } else
934                 pool = flist->file_pool;
935
936 #if EXTRA_ROUNDING > 0
937         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
938                 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
939 #endif
940
941         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
942                   + linkname_len;
943         bp = pool_alloc(pool, alloc_len, "recv_file_entry");
944
945         memset(bp, 0, extra_len + FILE_STRUCT_LEN);
946         bp += extra_len;
947         file = (struct file_struct *)bp;
948         bp += FILE_STRUCT_LEN;
949
950         memcpy(bp, basename, basename_len);
951
952 #ifdef SUPPORT_HARD_LINKS
953         if (xflags & XMIT_HLINKED
954 #ifndef CAN_HARDLINK_SYMLINK
955          && !S_ISLNK(mode)
956 #endif
957 #ifndef CAN_HARDLINK_SPECIAL
958          && !IS_SPECIAL(mode) && !IS_DEVICE(mode)
959 #endif
960         )
961                 file->flags |= FLAG_HLINKED;
962 #endif
963         file->modtime = (time_t)modtime;
964 #ifdef CAN_SET_NSEC
965         if (modtime_nsec) {
966                 file->flags |= FLAG_MOD_NSEC;
967                 F_MOD_NSEC(file) = modtime_nsec;
968         }
969 #endif
970         file->len32 = (uint32)file_length;
971 #if SIZEOF_INT64 >= 8
972         if (file_length > 0xFFFFFFFFu && S_ISREG(mode)) {
973 #if SIZEOF_CAPITAL_OFF_T < 8
974                 rprintf(FERROR, "Offset overflow: attempted 64-bit file-length\n");
975                 exit_cleanup(RERR_UNSUPPORTED);
976 #else
977                 file->flags |= FLAG_LENGTH64;
978                 F_HIGH_LEN(file) = (uint32)(file_length >> 32);
979 #endif
980         }
981 #endif
982         file->mode = mode;
983         if (preserve_uid)
984                 F_OWNER(file) = uid;
985         if (preserve_gid) {
986                 F_GROUP(file) = gid;
987                 file->flags |= gid_flags;
988         }
989         if (atimes_ndx && !S_ISDIR(mode))
990                 F_ATIME(file) = atime;
991         if (unsort_ndx)
992                 F_NDX(file) = flist->used + flist->ndx_start;
993
994         if (basename != thisname) {
995                 file->dirname = lastdir;
996                 F_DEPTH(file) = lastdir_depth + 1;
997         } else
998                 F_DEPTH(file) = 1;
999
1000         if (S_ISDIR(mode)) {
1001                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
1002                         F_DEPTH(file)--;
1003                 if (protocol_version >= 30) {
1004                         if (!(xflags & XMIT_NO_CONTENT_DIR)) {
1005                                 if (xflags & XMIT_TOP_DIR)
1006                                         file->flags |= FLAG_TOP_DIR;
1007                                 file->flags |= FLAG_CONTENT_DIR;
1008                         } else if (xflags & XMIT_TOP_DIR)
1009                                 file->flags |= FLAG_IMPLIED_DIR;
1010                 } else if (xflags & XMIT_TOP_DIR) {
1011                         in_del_hier = recurse;
1012                         del_hier_name_len = F_DEPTH(file) == 0 ? 0 : l1 + l2;
1013                         if (relative_paths && del_hier_name_len > 2
1014                             && lastname[del_hier_name_len-1] == '.'
1015                             && lastname[del_hier_name_len-2] == '/')
1016                                 del_hier_name_len -= 2;
1017                         file->flags |= FLAG_TOP_DIR | FLAG_CONTENT_DIR;
1018                 } else if (in_del_hier) {
1019                         if (!relative_paths || !del_hier_name_len
1020                          || (l1 >= del_hier_name_len
1021                           && lastname[del_hier_name_len] == '/'))
1022                                 file->flags |= FLAG_CONTENT_DIR;
1023                         else
1024                                 in_del_hier = 0;
1025                 }
1026         }
1027
1028         if (preserve_devices && IS_DEVICE(mode)) {
1029                 uint32 *devp = F_RDEV_P(file);
1030                 DEV_MAJOR(devp) = major(rdev);
1031                 DEV_MINOR(devp) = minor(rdev);
1032         }
1033
1034 #ifdef SUPPORT_LINKS
1035         if (linkname_len) {
1036                 bp += basename_len;
1037                 if (first_hlink_ndx >= flist->ndx_start) {
1038                         struct file_struct *first = flist->files[first_hlink_ndx - flist->ndx_start];
1039                         memcpy(bp, F_SYMLINK(first), linkname_len);
1040                 } else {
1041                         if (munge_symlinks) {
1042                                 strlcpy(bp, SYMLINK_PREFIX, linkname_len);
1043                                 bp += SYMLINK_PREFIX_LEN;
1044                                 linkname_len -= SYMLINK_PREFIX_LEN;
1045                         }
1046 #ifdef ICONV_OPTION
1047                         if (sender_symlink_iconv) {
1048                                 xbuf outbuf, inbuf;
1049
1050                                 alloc_len = linkname_len;
1051                                 linkname_len /= 2;
1052
1053                                 /* Read the symlink data into the end of our double-sized
1054                                  * buffer and then convert it into the right spot. */
1055                                 INIT_XBUF(inbuf, bp + alloc_len - linkname_len,
1056                                           linkname_len - 1, (size_t)-1);
1057                                 read_sbuf(f, inbuf.buf, inbuf.len);
1058                                 INIT_XBUF(outbuf, bp, 0, alloc_len);
1059
1060                                 if (iconvbufs(ic_recv, &inbuf, &outbuf, ICB_INIT) < 0) {
1061                                         io_error |= IOERR_GENERAL;
1062                                         rprintf(FERROR_XFER,
1063                                             "[%s] cannot convert symlink data for: %s (%s)\n",
1064                                             who_am_i(), full_fname(thisname), strerror(errno));
1065                                         bp = (char*)file->basename;
1066                                         *bp++ = '\0';
1067                                         outbuf.len = 0;
1068                                 }
1069                                 bp[outbuf.len] = '\0';
1070                         } else
1071 #endif
1072                                 read_sbuf(f, bp, linkname_len - 1);
1073                         if (sanitize_paths && !munge_symlinks && *bp)
1074                                 sanitize_path(bp, bp, "", lastdir_depth, SP_DEFAULT);
1075                 }
1076         }
1077 #endif
1078
1079 #ifdef SUPPORT_HARD_LINKS
1080         if (preserve_hard_links && xflags & XMIT_HLINKED) {
1081                 if (protocol_version >= 30) {
1082                         if (xflags & XMIT_HLINK_FIRST) {
1083                                 F_HL_GNUM(file) = flist->ndx_start + flist->used;
1084                         } else
1085                                 F_HL_GNUM(file) = first_hlink_ndx;
1086                 } else {
1087                         static int32 cnt = 0;
1088                         struct ht_int64_node *np;
1089                         int64 ino;
1090                         int32 ndx;
1091                         if (protocol_version < 26) {
1092                                 dev = read_int(f);
1093                                 ino = read_int(f);
1094                         } else {
1095                                 if (!(xflags & XMIT_SAME_DEV_pre30))
1096                                         dev = read_longint(f);
1097                                 ino = read_longint(f);
1098                         }
1099                         np = idev_find(dev, ino);
1100                         ndx = (int32)(long)np->data; /* is -1 when new */
1101                         if (ndx < 0) {
1102                                 np->data = (void*)(long)cnt;
1103                                 ndx = cnt++;
1104                         }
1105                         F_HL_GNUM(file) = ndx;
1106                 }
1107         }
1108 #endif
1109
1110         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
1111                 if (S_ISREG(mode))
1112                         bp = F_SUM(file);
1113                 else {
1114                         /* Prior to 28, we get a useless set of nulls. */
1115                         bp = tmp_sum;
1116                 }
1117                 if (first_hlink_ndx >= flist->ndx_start) {
1118                         struct file_struct *first = flist->files[first_hlink_ndx - flist->ndx_start];
1119                         memcpy(bp, F_SUM(first), flist_csum_len);
1120                 } else
1121                         read_buf(f, bp, flist_csum_len);
1122         }
1123
1124 #ifdef SUPPORT_ACLS
1125         if (preserve_acls && !S_ISLNK(mode))
1126                 receive_acl(f, file);
1127 #endif
1128 #ifdef SUPPORT_XATTRS
1129         if (preserve_xattrs)
1130                 receive_xattr(f, file);
1131 #endif
1132
1133         if (S_ISREG(mode) || S_ISLNK(mode))
1134                 stats.total_size += file_length;
1135
1136         return file;
1137 }
1138
1139 /* Create a file_struct for a named file by reading its stat() information
1140  * and performing extensive checks against global options.
1141  *
1142  * Returns a pointer to the new file struct, or NULL if there was an error
1143  * or this file should be excluded.
1144  *
1145  * Note: Any error (here or in send_file_name) that results in the omission of
1146  * an existent source file from the file list should set
1147  * "io_error |= IOERR_GENERAL" to avoid deletion of the file from the
1148  * destination if --delete is on. */
1149 struct file_struct *make_file(const char *fname, struct file_list *flist,
1150                               STRUCT_STAT *stp, int flags, int filter_level)
1151 {
1152         static char *lastdir;
1153         static int lastdir_len = -1;
1154         struct file_struct *file;
1155         char thisname[MAXPATHLEN];
1156         char linkname[MAXPATHLEN];
1157         int alloc_len, basename_len, linkname_len;
1158         int extra_len = file_extra_cnt * EXTRA_LEN;
1159         const char *basename;
1160         alloc_pool_t *pool;
1161         STRUCT_STAT st;
1162         char *bp;
1163
1164         if (strlcpy(thisname, fname, sizeof thisname) >= sizeof thisname) {
1165                 io_error |= IOERR_GENERAL;
1166                 rprintf(FERROR_XFER, "skipping overly long name: %s\n", fname);
1167                 return NULL;
1168         }
1169         clean_fname(thisname, 0);
1170         if (sanitize_paths)
1171                 sanitize_path(thisname, thisname, "", 0, SP_DEFAULT);
1172
1173         if (stp && (S_ISDIR(stp->st_mode) || IS_MISSING_FILE(*stp))) {
1174                 /* This is needed to handle a "symlink/." with a --relative
1175                  * dir, or a request to delete a specific file. */
1176                 st = *stp;
1177                 *linkname = '\0'; /* make IBM code checker happy */
1178         } else if (readlink_stat(thisname, &st, linkname) != 0) {
1179                 int save_errno = errno;
1180                 /* See if file is excluded before reporting an error. */
1181                 if (filter_level != NO_FILTERS
1182                  && (is_excluded(thisname, 0, filter_level)
1183                   || is_excluded(thisname, 1, filter_level))) {
1184                         if (ignore_perishable && save_errno != ENOENT)
1185                                 non_perishable_cnt++;
1186                         return NULL;
1187                 }
1188                 if (save_errno == ENOENT) {
1189 #ifdef SUPPORT_LINKS
1190                         /* When our options tell us to follow a symlink that
1191                          * points nowhere, tell the user about the symlink
1192                          * instead of giving a "vanished" message.  We only
1193                          * dereference a symlink if one of the --copy*links
1194                          * options was specified, so there's no need for the
1195                          * extra lstat() if one of these options isn't on. */
1196                         if ((copy_links || copy_unsafe_links || copy_dirlinks)
1197                          && x_lstat(thisname, &st, NULL) == 0
1198                          && S_ISLNK(st.st_mode)) {
1199                                 io_error |= IOERR_GENERAL;
1200                                 rprintf(FERROR_XFER, "symlink has no referent: %s\n",
1201                                         full_fname(thisname));
1202                         } else
1203 #endif
1204                         {
1205                                 enum logcode c = am_daemon && protocol_version < 28
1206                                                ? FERROR : FWARNING;
1207                                 io_error |= IOERR_VANISHED;
1208                                 rprintf(c, "file has vanished: %s\n",
1209                                         full_fname(thisname));
1210                         }
1211                 } else {
1212                         io_error |= IOERR_GENERAL;
1213                         rsyserr(FERROR_XFER, save_errno, "readlink_stat(%s) failed",
1214                                 full_fname(thisname));
1215                 }
1216                 return NULL;
1217         } else if (IS_MISSING_FILE(st)) {
1218                 io_error |= IOERR_GENERAL;
1219                 rprintf(FINFO, "skipping file with bogus (zero) st_mode: %s\n",
1220                         full_fname(thisname));
1221                 return NULL;
1222         }
1223
1224         if (filter_level == NO_FILTERS)
1225                 goto skip_filters;
1226
1227         if (S_ISDIR(st.st_mode)) {
1228                 if (!xfer_dirs) {
1229                         rprintf(FINFO, "skipping directory %s\n", thisname);
1230                         return NULL;
1231                 }
1232                 /* -x only affects dirs because we need to avoid recursing
1233                  * into a mount-point directory, not to avoid copying a
1234                  * symlinked file if -L (or similar) was specified. */
1235                 if (one_file_system && st.st_dev != filesystem_dev
1236                  && BITS_SETnUNSET(flags, FLAG_CONTENT_DIR, FLAG_TOP_DIR)) {
1237                         if (one_file_system > 1) {
1238                                 if (INFO_GTE(MOUNT, 1)) {
1239                                         rprintf(FINFO,
1240                                             "[%s] skipping mount-point dir %s\n",
1241                                             who_am_i(), thisname);
1242                                 }
1243                                 return NULL;
1244                         }
1245                         flags |= FLAG_MOUNT_DIR;
1246                         flags &= ~FLAG_CONTENT_DIR;
1247                 }
1248         } else
1249                 flags &= ~FLAG_CONTENT_DIR;
1250
1251         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level)) {
1252                 if (ignore_perishable)
1253                         non_perishable_cnt++;
1254                 return NULL;
1255         }
1256
1257         if (lp_ignore_nonreadable(module_id)) {
1258 #ifdef SUPPORT_LINKS
1259                 if (!S_ISLNK(st.st_mode))
1260 #endif
1261                         if (access(thisname, R_OK) != 0)
1262                                 return NULL;
1263         }
1264
1265   skip_filters:
1266
1267         /* Only divert a directory in the main transfer. */
1268         if (flist) {
1269                 if (flist->prev && S_ISDIR(st.st_mode)
1270                  && flags & FLAG_DIVERT_DIRS) {
1271                         /* Room for parent/sibling/next-child info. */
1272                         extra_len += DIRNODE_EXTRA_CNT * EXTRA_LEN;
1273                         if (relative_paths)
1274                                 extra_len += PTR_EXTRA_CNT * EXTRA_LEN;
1275                         pool = dir_flist->file_pool;
1276                 } else
1277                         pool = flist->file_pool;
1278         } else {
1279 #ifdef SUPPORT_ACLS
1280                 /* Directories need an extra int32 for the default ACL. */
1281                 if (preserve_acls && S_ISDIR(st.st_mode))
1282                         extra_len += EXTRA_LEN;
1283 #endif
1284                 pool = NULL;
1285         }
1286
1287         if (DEBUG_GTE(FLIST, 2)) {
1288                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
1289                         who_am_i(), thisname, filter_level);
1290         }
1291
1292         if ((basename = strrchr(thisname, '/')) != NULL) {
1293                 int len = basename++ - thisname;
1294                 if (len != lastdir_len || memcmp(thisname, lastdir, len) != 0) {
1295                         lastdir = new_array(char, len + 1);
1296                         memcpy(lastdir, thisname, len);
1297                         lastdir[len] = '\0';
1298                         lastdir_len = len;
1299                 }
1300         } else
1301                 basename = thisname;
1302         basename_len = strlen(basename) + 1; /* count the '\0' */
1303
1304 #ifdef SUPPORT_LINKS
1305         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
1306 #else
1307         linkname_len = 0;
1308 #endif
1309
1310 #ifdef ST_MTIME_NSEC
1311         if (st.ST_MTIME_NSEC && protocol_version >= 31)
1312                 extra_len += EXTRA_LEN;
1313 #endif
1314 #if SIZEOF_CAPITAL_OFF_T >= 8
1315         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode))
1316                 extra_len += EXTRA_LEN;
1317 #endif
1318
1319         if (always_checksum && am_sender && S_ISREG(st.st_mode)) {
1320                 file_checksum(thisname, &st, tmp_sum);
1321                 if (sender_keeps_checksum)
1322                         extra_len += SUM_EXTRA_CNT * EXTRA_LEN;
1323         }
1324
1325 #if EXTRA_ROUNDING > 0
1326         if (extra_len & (EXTRA_ROUNDING * EXTRA_LEN))
1327                 extra_len = (extra_len | (EXTRA_ROUNDING * EXTRA_LEN)) + EXTRA_LEN;
1328 #endif
1329
1330         alloc_len = FILE_STRUCT_LEN + extra_len + basename_len
1331                   + linkname_len;
1332         if (pool)
1333                 bp = pool_alloc(pool, alloc_len, "make_file");
1334         else
1335                 bp = new_array(char, alloc_len);
1336
1337         memset(bp, 0, extra_len + FILE_STRUCT_LEN);
1338         bp += extra_len;
1339         file = (struct file_struct *)bp;
1340         bp += FILE_STRUCT_LEN;
1341
1342         memcpy(bp, basename, basename_len);
1343
1344 #ifdef SUPPORT_HARD_LINKS
1345         if (preserve_hard_links && flist && flist->prev) {
1346                 if (protocol_version >= 28
1347                  ? (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
1348                  : S_ISREG(st.st_mode)) {
1349                         tmp_dev = (int64)st.st_dev;
1350                         tmp_ino = (int64)st.st_ino;
1351                 } else
1352                         tmp_dev = -1;
1353         }
1354 #endif
1355
1356 #ifdef HAVE_STRUCT_STAT_ST_RDEV
1357         if (IS_DEVICE(st.st_mode)) {
1358                 tmp_rdev = st.st_rdev;
1359                 st.st_size = 0;
1360         } else if (IS_SPECIAL(st.st_mode))
1361                 st.st_size = 0;
1362 #endif
1363
1364         file->flags = flags;
1365         file->modtime = st.st_mtime;
1366 #ifdef ST_MTIME_NSEC
1367         if (st.ST_MTIME_NSEC && protocol_version >= 31) {
1368                 file->flags |= FLAG_MOD_NSEC;
1369                 F_MOD_NSEC(file) = st.ST_MTIME_NSEC;
1370         }
1371 #endif
1372         file->len32 = (uint32)st.st_size;
1373 #if SIZEOF_CAPITAL_OFF_T >= 8
1374         if (st.st_size > 0xFFFFFFFFu && S_ISREG(st.st_mode)) {
1375                 file->flags |= FLAG_LENGTH64;
1376                 F_HIGH_LEN(file) = (uint32)(st.st_size >> 32);
1377         }
1378 #endif
1379         file->mode = st.st_mode;
1380         if (preserve_uid)
1381                 F_OWNER(file) = st.st_uid;
1382         if (preserve_gid)
1383                 F_GROUP(file) = st.st_gid;
1384         if (am_generator && st.st_uid == our_uid)
1385                 file->flags |= FLAG_OWNED_BY_US;
1386         if (atimes_ndx && !S_ISDIR(file->mode))
1387                 F_ATIME(file) = st.st_atime;
1388
1389         if (basename != thisname)
1390                 file->dirname = lastdir;
1391
1392 #ifdef SUPPORT_LINKS
1393         if (linkname_len)
1394                 memcpy(bp + basename_len, linkname, linkname_len);
1395 #endif
1396
1397         if (am_sender)
1398                 F_PATHNAME(file) = pathname;
1399         else if (!pool)
1400                 F_DEPTH(file) = extra_len / EXTRA_LEN;
1401
1402         if (basename_len == 0+1) {
1403                 if (!pool)
1404                         unmake_file(file);
1405                 return NULL;
1406         }
1407
1408         if (sender_keeps_checksum && S_ISREG(st.st_mode))
1409                 memcpy(F_SUM(file), tmp_sum, flist_csum_len);
1410
1411         if (unsort_ndx)
1412                 F_NDX(file) = stats.num_dirs;
1413
1414         return file;
1415 }
1416
1417 OFF_T get_device_size(int fd, const char *fname)
1418 {
1419         OFF_T off = lseek(fd, 0, SEEK_END);
1420
1421         if (off == (OFF_T) -1) {
1422                 rsyserr(FERROR, errno, "failed to get device size via seek: %s", fname);
1423                 return 0;
1424         }
1425         if (lseek(fd, 0, SEEK_SET) != 0)
1426                 rsyserr(FERROR, errno, "failed to seek device back to start: %s", fname);
1427
1428         return off;
1429 }
1430
1431 /* Only called for temporary file_struct entries created by make_file(). */
1432 void unmake_file(struct file_struct *file)
1433 {
1434         free(REQ_EXTRA(file, F_DEPTH(file)));
1435 }
1436
1437 static struct file_struct *send_file_name(int f, struct file_list *flist,
1438                                           const char *fname, STRUCT_STAT *stp,
1439                                           int flags, int filter_level)
1440 {
1441         struct file_struct *file;
1442
1443         file = make_file(fname, flist, stp, flags, filter_level);
1444         if (!file)
1445                 return NULL;
1446
1447         if (chmod_modes && !S_ISLNK(file->mode) && file->mode)
1448                 file->mode = tweak_mode(file->mode, chmod_modes);
1449
1450         if (f >= 0) {
1451                 char fbuf[MAXPATHLEN];
1452 #ifdef SUPPORT_LINKS
1453                 const char *symlink_name;
1454                 int symlink_len;
1455 #ifdef ICONV_OPTION
1456                 char symlink_buf[MAXPATHLEN];
1457 #endif
1458 #endif
1459 #if defined SUPPORT_ACLS || defined SUPPORT_XATTRS
1460                 stat_x sx;
1461                 init_stat_x(&sx);
1462 #endif
1463
1464 #ifdef SUPPORT_LINKS
1465                 if (preserve_links && S_ISLNK(file->mode)) {
1466                         symlink_name = F_SYMLINK(file);
1467                         symlink_len = strlen(symlink_name);
1468                         if (symlink_len == 0) {
1469                                 io_error |= IOERR_GENERAL;
1470                                 f_name(file, fbuf);
1471                                 rprintf(FERROR_XFER,
1472                                     "skipping symlink with 0-length value: %s\n",
1473                                     full_fname(fbuf));
1474                                 return NULL;
1475                         }
1476                 } else {
1477                         symlink_name = NULL;
1478                         symlink_len = 0;
1479                 }
1480 #endif
1481
1482 #ifdef ICONV_OPTION
1483                 if (ic_send != (iconv_t)-1) {
1484                         xbuf outbuf, inbuf;
1485
1486                         INIT_CONST_XBUF(outbuf, fbuf);
1487
1488                         if (file->dirname) {
1489                                 INIT_XBUF_STRLEN(inbuf, (char*)file->dirname);
1490                                 outbuf.size -= 2; /* Reserve room for '/' & 1 more char. */
1491                                 if (iconvbufs(ic_send, &inbuf, &outbuf, ICB_INIT) < 0)
1492                                         goto convert_error;
1493                                 outbuf.size += 2;
1494                                 fbuf[outbuf.len++] = '/';
1495                         }
1496
1497                         INIT_XBUF_STRLEN(inbuf, (char*)file->basename);
1498                         if (iconvbufs(ic_send, &inbuf, &outbuf, ICB_INIT) < 0) {
1499                           convert_error:
1500                                 io_error |= IOERR_GENERAL;
1501                                 rprintf(FERROR_XFER,
1502                                     "[%s] cannot convert filename: %s (%s)\n",
1503                                     who_am_i(), f_name(file, fbuf), strerror(errno));
1504                                 return NULL;
1505                         }
1506                         fbuf[outbuf.len] = '\0';
1507
1508 #ifdef SUPPORT_LINKS
1509                         if (symlink_len && sender_symlink_iconv) {
1510                                 INIT_XBUF(inbuf, (char*)symlink_name, symlink_len, (size_t)-1);
1511                                 INIT_CONST_XBUF(outbuf, symlink_buf);
1512                                 if (iconvbufs(ic_send, &inbuf, &outbuf, ICB_INIT) < 0) {
1513                                         io_error |= IOERR_GENERAL;
1514                                         f_name(file, fbuf);
1515                                         rprintf(FERROR_XFER,
1516                                             "[%s] cannot convert symlink data for: %s (%s)\n",
1517                                             who_am_i(), full_fname(fbuf), strerror(errno));
1518                                         return NULL;
1519                                 }
1520                                 symlink_buf[outbuf.len] = '\0';
1521
1522                                 symlink_name = symlink_buf;
1523                                 symlink_len = outbuf.len;
1524                         }
1525 #endif
1526                 } else
1527 #endif
1528                         f_name(file, fbuf);
1529
1530 #ifdef SUPPORT_ACLS
1531                 if (preserve_acls && !S_ISLNK(file->mode)) {
1532                         sx.st.st_mode = file->mode;
1533                         if (get_acl(fname, &sx) < 0) {
1534                                 io_error |= IOERR_GENERAL;
1535                                 return NULL;
1536                         }
1537                 }
1538 #endif
1539 #ifdef SUPPORT_XATTRS
1540                 if (preserve_xattrs) {
1541                         sx.st.st_mode = file->mode;
1542                         if (get_xattr(fname, &sx) < 0) {
1543                                 io_error |= IOERR_GENERAL;
1544                                 return NULL;
1545                         }
1546                 }
1547 #endif
1548
1549                 send_file_entry(f, fbuf, file,
1550 #ifdef SUPPORT_LINKS
1551                                 symlink_name, symlink_len,
1552 #endif
1553                                 flist->used, flist->ndx_start);
1554
1555 #ifdef SUPPORT_ACLS
1556                 if (preserve_acls && !S_ISLNK(file->mode)) {
1557                         send_acl(f, &sx);
1558                         free_acl(&sx);
1559                 }
1560 #endif
1561 #ifdef SUPPORT_XATTRS
1562                 if (preserve_xattrs) {
1563                         F_XATTR(file) = send_xattr(f, &sx);
1564                         free_xattr(&sx);
1565                 }
1566 #endif
1567         }
1568
1569         maybe_emit_filelist_progress(flist->used + flist_count_offset);
1570
1571         flist_expand(flist, 1);
1572         flist->files[flist->used++] = file;
1573
1574         return file;
1575 }
1576
1577 static void send_if_directory(int f, struct file_list *flist,
1578                               struct file_struct *file,
1579                               char *fbuf, unsigned int ol,
1580                               int flags)
1581 {
1582         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
1583
1584         if (S_ISDIR(file->mode)
1585             && !(file->flags & FLAG_MOUNT_DIR) && f_name(file, fbuf)) {
1586                 void *save_filters;
1587                 unsigned int len = strlen(fbuf);
1588                 if (len > 1 && fbuf[len-1] == '/')
1589                         fbuf[--len] = '\0';
1590                 save_filters = push_local_filters(fbuf, len);
1591                 send_directory(f, flist, fbuf, len, flags);
1592                 pop_local_filters(save_filters);
1593                 fbuf[ol] = '\0';
1594                 if (is_dot_dir)
1595                         fbuf[ol-1] = '.';
1596         }
1597 }
1598
1599 static int file_compare(const void *file1, const void *file2)
1600 {
1601         return f_name_cmp(*(struct file_struct **)file1,
1602                           *(struct file_struct **)file2);
1603 }
1604
1605 /* The guts of a merge-sort algorithm.  This was derived from the glibc
1606  * version, but I (Wayne) changed the merge code to do less copying and
1607  * to require only half the amount of temporary memory. */
1608 static void fsort_tmp(struct file_struct **fp, size_t num,
1609                       struct file_struct **tmp)
1610 {
1611         struct file_struct **f1, **f2, **t;
1612         size_t n1, n2;
1613
1614         n1 = num / 2;
1615         n2 = num - n1;
1616         f1 = fp;
1617         f2 = fp + n1;
1618
1619         if (n1 > 1)
1620                 fsort_tmp(f1, n1, tmp);
1621         if (n2 > 1)
1622                 fsort_tmp(f2, n2, tmp);
1623
1624         while (f_name_cmp(*f1, *f2) <= 0) {
1625                 if (!--n1)
1626                         return;
1627                 f1++;
1628         }
1629
1630         t = tmp;
1631         memcpy(t, f1, n1 * PTR_SIZE);
1632
1633         *f1++ = *f2++, n2--;
1634
1635         while (n1 > 0 && n2 > 0) {
1636                 if (f_name_cmp(*t, *f2) <= 0)
1637                         *f1++ = *t++, n1--;
1638                 else
1639                         *f1++ = *f2++, n2--;
1640         }
1641
1642         if (n1 > 0)
1643                 memcpy(f1, t, n1 * PTR_SIZE);
1644 }
1645
1646 /* This file-struct sorting routine makes sure that any identical names in
1647  * the file list stay in the same order as they were in the original list.
1648  * This is particularly vital in inc_recurse mode where we expect a sort
1649  * on the flist to match the exact order of a sort on the dir_flist. */
1650 static void fsort(struct file_struct **fp, size_t num)
1651 {
1652         if (num <= 1)
1653                 return;
1654
1655         if (use_qsort)
1656                 qsort(fp, num, PTR_SIZE, file_compare);
1657         else {
1658                 struct file_struct **tmp = new_array(struct file_struct *, (num+1) / 2);
1659                 fsort_tmp(fp, num, tmp);
1660                 free(tmp);
1661         }
1662 }
1663
1664 /* We take an entire set of sibling dirs from the sorted flist and link them
1665  * into the tree, setting the appropriate parent/child/sibling pointers. */
1666 static void add_dirs_to_tree(int parent_ndx, struct file_list *from_flist,
1667                              int dir_cnt)
1668 {
1669         int i;
1670         int32 *dp = NULL;
1671         int32 *parent_dp = parent_ndx < 0 ? NULL
1672                          : F_DIR_NODE_P(dir_flist->sorted[parent_ndx]);
1673
1674         /* The sending side is adding entries to dir_flist in sorted order, so sorted & files are the same. */
1675         flist_expand(dir_flist, dir_cnt);
1676         dir_flist->sorted = dir_flist->files;
1677
1678         for (i = 0; dir_cnt; i++) {
1679                 struct file_struct *file = from_flist->sorted[i];
1680
1681                 if (!S_ISDIR(file->mode))
1682                         continue;
1683
1684                 dir_flist->files[dir_flist->used++] = file;
1685                 dir_cnt--;
1686
1687                 if (file->basename[0] == '.' && file->basename[1] == '\0')
1688                         continue;
1689
1690                 if (dp)
1691                         DIR_NEXT_SIBLING(dp) = dir_flist->used - 1;
1692                 else if (parent_dp)
1693                         DIR_FIRST_CHILD(parent_dp) = dir_flist->used - 1;
1694                 else
1695                         send_dir_ndx = dir_flist->used - 1;
1696
1697                 dp = F_DIR_NODE_P(file);
1698                 DIR_PARENT(dp) = parent_ndx;
1699                 DIR_FIRST_CHILD(dp) = -1;
1700         }
1701         if (dp)
1702                 DIR_NEXT_SIBLING(dp) = -1;
1703 }
1704
1705 static void interpret_stat_error(const char *fname, int is_dir)
1706 {
1707         if (errno == ENOENT) {
1708                 io_error |= IOERR_VANISHED;
1709                 rprintf(FWARNING, "%s has vanished: %s\n",
1710                         is_dir ? "directory" : "file", full_fname(fname));
1711         } else {
1712                 io_error |= IOERR_GENERAL;
1713                 rsyserr(FERROR_XFER, errno, "link_stat %s failed",
1714                         full_fname(fname));
1715         }
1716 }
1717
1718 /* This function is normally called by the sender, but the receiving side also
1719  * calls it from get_dirlist() with f set to -1 so that we just construct the
1720  * file list in memory without sending it over the wire.  Also, get_dirlist()
1721  * might call this with f set to -2, which also indicates that local filter
1722  * rules should be ignored. */
1723 static void send_directory(int f, struct file_list *flist, char *fbuf, int len,
1724                            int flags)
1725 {
1726         struct dirent *di;
1727         unsigned remainder;
1728         char *p;
1729         DIR *d;
1730         int divert_dirs = (flags & FLAG_DIVERT_DIRS) != 0;
1731         int start = flist->used;
1732         int filter_level = f == -2 ? SERVER_FILTERS : ALL_FILTERS;
1733
1734         assert(flist != NULL);
1735
1736         if (!(d = opendir(fbuf))) {
1737                 if (errno == ENOENT) {
1738                         if (am_sender) /* Can abuse this for vanished error w/ENOENT: */
1739                                 interpret_stat_error(fbuf, True);
1740                         return;
1741                 }
1742                 if (errno == ENOTDIR && (flags & FLAG_PERHAPS_DIR))
1743                         return;
1744                 io_error |= IOERR_GENERAL;
1745                 rsyserr(FERROR_XFER, errno, "opendir %s failed", full_fname(fbuf));
1746                 return;
1747         }
1748
1749         p = fbuf + len;
1750         if (len == 1 && *fbuf == '/')
1751                 remainder = MAXPATHLEN - 1;
1752         else if (len < MAXPATHLEN-1) {
1753                 *p++ = '/';
1754                 *p = '\0';
1755                 remainder = MAXPATHLEN - (len + 1);
1756         } else
1757                 remainder = 0;
1758
1759         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1760                 unsigned name_len;
1761                 char *dname = d_name(di);
1762                 if (dname[0] == '.' && (dname[1] == '\0'
1763                     || (dname[1] == '.' && dname[2] == '\0')))
1764                         continue;
1765                 name_len = strlcpy(p, dname, remainder);
1766                 if (name_len >= remainder) {
1767                         char save = fbuf[len];
1768                         fbuf[len] = '\0';
1769                         io_error |= IOERR_GENERAL;
1770                         rprintf(FERROR_XFER,
1771                                 "filename overflows max-path len by %u: %s/%s\n",
1772                                 name_len - remainder + 1, fbuf, dname);
1773                         fbuf[len] = save;
1774                         continue;
1775                 }
1776                 if (dname[0] == '\0') {
1777                         io_error |= IOERR_GENERAL;
1778                         rprintf(FERROR_XFER,
1779                                 "cannot send file with empty name in %s\n",
1780                                 full_fname(fbuf));
1781                         continue;
1782                 }
1783
1784                 send_file_name(f, flist, fbuf, NULL, flags, filter_level);
1785         }
1786
1787         fbuf[len] = '\0';
1788
1789         if (errno) {
1790                 io_error |= IOERR_GENERAL;
1791                 rsyserr(FERROR_XFER, errno, "readdir(%s)", full_fname(fbuf));
1792         }
1793
1794         closedir(d);
1795
1796         if (f >= 0 && recurse && !divert_dirs) {
1797                 int i, end = flist->used - 1;
1798                 /* send_if_directory() bumps flist->used, so use "end". */
1799                 for (i = start; i <= end; i++)
1800                         send_if_directory(f, flist, flist->files[i], fbuf, len, flags);
1801         }
1802 }
1803
1804 static void send_implied_dirs(int f, struct file_list *flist, char *fname,
1805                               char *start, char *limit, int flags, char name_type)
1806 {
1807         static char lastpath[MAXPATHLEN] = "";
1808         static int lastpath_len = 0;
1809         static struct file_struct *lastpath_struct = NULL;
1810         struct file_struct *file;
1811         item_list *relname_list;
1812         relnamecache **rnpp;
1813         int len, need_new_dir, depth = 0;
1814         filter_rule_list save_filter_list = filter_list;
1815
1816         flags = (flags | FLAG_IMPLIED_DIR) & ~(FLAG_TOP_DIR | FLAG_CONTENT_DIR);
1817         filter_list.head = filter_list.tail = NULL; /* Don't filter implied dirs. */
1818
1819         if (inc_recurse) {
1820                 if (lastpath_struct && F_PATHNAME(lastpath_struct) == pathname
1821                  && lastpath_len == limit - fname
1822                  && strncmp(lastpath, fname, lastpath_len) == 0)
1823                         need_new_dir = 0;
1824                 else
1825                         need_new_dir = 1;
1826         } else {
1827                 char *tp = fname, *lp = lastpath;
1828                 /* Skip any initial directories in our path that we
1829                  * have in common with lastpath. */
1830                 assert(start == fname);
1831                 for ( ; ; tp++, lp++) {
1832                         if (tp == limit) {
1833                                 if (*lp == '/' || *lp == '\0')
1834                                         goto done;
1835                                 break;
1836                         }
1837                         if (*lp != *tp)
1838                                 break;
1839                         if (*tp == '/') {
1840                                 start = tp;
1841                                 depth++;
1842                         }
1843                 }
1844                 need_new_dir = 1;
1845         }
1846
1847         if (need_new_dir) {
1848                 int save_copy_links = copy_links;
1849                 int save_xfer_dirs = xfer_dirs;
1850                 char *slash;
1851
1852                 copy_links = xfer_dirs = 1;
1853
1854                 *limit = '\0';
1855
1856                 for (slash = start; (slash = strchr(slash+1, '/')) != NULL; ) {
1857                         *slash = '\0';
1858                         file = send_file_name(f, flist, fname, NULL, flags, ALL_FILTERS);
1859                         depth++;
1860                         if (!inc_recurse && file && S_ISDIR(file->mode))
1861                                 change_local_filter_dir(fname, strlen(fname), depth);
1862                         *slash = '/';
1863                 }
1864
1865                 file = send_file_name(f, flist, fname, NULL, flags, ALL_FILTERS);
1866                 if (inc_recurse) {
1867                         if (file && !S_ISDIR(file->mode))
1868                                 file = NULL;
1869                         lastpath_struct = file;
1870                 } else if (file && S_ISDIR(file->mode))
1871                         change_local_filter_dir(fname, strlen(fname), ++depth);
1872
1873                 strlcpy(lastpath, fname, sizeof lastpath);
1874                 lastpath_len = limit - fname;
1875
1876                 *limit = '/';
1877
1878                 copy_links = save_copy_links;
1879                 xfer_dirs = save_xfer_dirs;
1880
1881                 if (!inc_recurse)
1882                         goto done;
1883         }
1884
1885         if (!lastpath_struct)
1886                 goto done; /* dir must have vanished */
1887
1888         len = strlen(limit+1);
1889         memcpy(&relname_list, F_DIR_RELNAMES_P(lastpath_struct), sizeof relname_list);
1890         if (!relname_list) {
1891                 relname_list = new0(item_list);
1892                 memcpy(F_DIR_RELNAMES_P(lastpath_struct), &relname_list, sizeof relname_list);
1893         }
1894         rnpp = EXPAND_ITEM_LIST(relname_list, relnamecache *, 32);
1895         *rnpp = (relnamecache*)new_array(char, RELNAMECACHE_LEN + len + 1);
1896         (*rnpp)->name_type = name_type;
1897         strlcpy((*rnpp)->fname, limit+1, len + 1);
1898
1899 done:
1900         filter_list = save_filter_list;
1901 }
1902
1903 static NORETURN void fatal_unsafe_io_error(void)
1904 {
1905         /* This (sadly) can only happen when pushing data because
1906          * the sender does not know about what kind of delete
1907          * is in effect on the receiving side when pulling. */
1908         rprintf(FERROR_XFER, "FATAL I/O ERROR: dying to avoid a --delete-%s issue with a pre-3.0.7 receiver.\n",
1909                 delete_during == 2 ? "delay" : "during");
1910         exit_cleanup(RERR_UNSUPPORTED);
1911 }
1912
1913 static void send1extra(int f, struct file_struct *file, struct file_list *flist)
1914 {
1915         char fbuf[MAXPATHLEN];
1916         item_list *relname_list;
1917         int len, dlen, flags = FLAG_DIVERT_DIRS | FLAG_CONTENT_DIR;
1918         size_t j;
1919
1920         f_name(file, fbuf);
1921         dlen = strlen(fbuf);
1922
1923         if (!change_pathname(file, NULL, 0))
1924                 exit_cleanup(RERR_FILESELECT);
1925
1926         change_local_filter_dir(fbuf, dlen, send_dir_depth);
1927
1928         if (file->flags & FLAG_CONTENT_DIR) {
1929                 if (one_file_system) {
1930                         STRUCT_STAT st;
1931                         if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
1932                                 interpret_stat_error(fbuf, True);
1933                                 return;
1934                         }
1935                         filesystem_dev = st.st_dev;
1936                 }
1937                 send_directory(f, flist, fbuf, dlen, flags);
1938         }
1939
1940         if (!relative_paths)
1941                 return;
1942
1943         memcpy(&relname_list, F_DIR_RELNAMES_P(file), sizeof relname_list);
1944         if (!relname_list)
1945                 return;
1946
1947         for (j = 0; j < relname_list->count; j++) {
1948                 char *slash;
1949                 relnamecache *rnp = ((relnamecache**)relname_list->items)[j];
1950                 char name_type = rnp->name_type;
1951
1952                 fbuf[dlen] = '/';
1953                 len = strlcpy(fbuf + dlen + 1, rnp->fname, sizeof fbuf - dlen - 1);
1954                 free(rnp);
1955                 if (len >= (int)sizeof fbuf)
1956                         continue; /* Impossible... */
1957
1958                 slash = strchr(fbuf+dlen+1, '/');
1959                 if (slash) {
1960                         send_implied_dirs(f, flist, fbuf, fbuf+dlen+1, slash, flags, name_type);
1961                         continue;
1962                 }
1963
1964                 if (name_type != NORMAL_NAME) {
1965                         STRUCT_STAT st;
1966                         if (name_type == MISSING_NAME)
1967                                 memset(&st, 0, sizeof st);
1968                         else if (link_stat(fbuf, &st, 1) != 0) {
1969                                 interpret_stat_error(fbuf, True);
1970                                 continue;
1971                         }
1972                         send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR | flags, ALL_FILTERS);
1973                 } else
1974                         send_file_name(f, flist, fbuf, NULL, FLAG_TOP_DIR | flags, ALL_FILTERS);
1975         }
1976
1977         free(relname_list);
1978 }
1979
1980 static void write_end_of_flist(int f, int send_io_error)
1981 {
1982         if (xfer_flags_as_varint) {
1983                 write_varint(f, 0);
1984                 write_varint(f, send_io_error ? io_error : 0);
1985         } else if (send_io_error) {
1986                 write_shortint(f, XMIT_EXTENDED_FLAGS|XMIT_IO_ERROR_ENDLIST);
1987                 write_varint(f, io_error);
1988         } else
1989                 write_byte(f, 0);
1990 }
1991
1992 void send_extra_file_list(int f, int at_least)
1993 {
1994         struct file_list *flist;
1995         int64 start_write;
1996         uint16 prev_flags;
1997         int save_io_error = io_error;
1998
1999         if (flist_eof)
2000                 return;
2001
2002         if (at_least < 0)
2003                 at_least = file_total - file_old_total + 1;
2004
2005         /* Keep sending data until we have the requested number of
2006          * files in the upcoming file-lists. */
2007         while (file_total - file_old_total < at_least) {
2008                 struct file_struct *file = dir_flist->sorted[send_dir_ndx];
2009                 int dir_ndx, dstart = stats.num_dirs;
2010                 const char *pathname = F_PATHNAME(file);
2011                 int32 *dp;
2012
2013                 flist = flist_new(0, "send_extra_file_list");
2014                 start_write = stats.total_written;
2015
2016                 if (unsort_ndx)
2017                         dir_ndx = F_NDX(file);
2018                 else
2019                         dir_ndx = send_dir_ndx;
2020                 write_ndx(f, NDX_FLIST_OFFSET - dir_ndx);
2021                 flist->parent_ndx = send_dir_ndx; /* the sending side must remember the sorted ndx value */
2022
2023                 send1extra(f, file, flist);
2024                 prev_flags = file->flags;
2025                 dp = F_DIR_NODE_P(file);
2026
2027                 /* If there are any duplicate directory names that follow, we
2028                  * send all the dirs together in one file-list.  The dir_flist
2029                  * tree links all the child subdirs onto the last dup dir. */
2030                 while ((dir_ndx = DIR_NEXT_SIBLING(dp)) >= 0
2031                     && dir_flist->sorted[dir_ndx]->flags & FLAG_DUPLICATE) {
2032                         send_dir_ndx = dir_ndx;
2033                         file = dir_flist->sorted[dir_ndx];
2034                         /* Try to avoid some duplicate scanning of identical dirs. */
2035                         if (F_PATHNAME(file) == pathname && prev_flags & FLAG_CONTENT_DIR)
2036                                 file->flags &= ~FLAG_CONTENT_DIR;
2037                         send1extra(f, file, flist);
2038                         prev_flags = file->flags;
2039                         dp = F_DIR_NODE_P(file);
2040                 }
2041
2042                 if (io_error == save_io_error || ignore_errors)
2043                         write_end_of_flist(f, 0);
2044                 else if (use_safe_inc_flist)
2045                         write_end_of_flist(f, 1);
2046                 else {
2047                         if (delete_during)
2048                                 fatal_unsafe_io_error();
2049                         write_end_of_flist(f, 0);
2050                 }
2051
2052                 if (need_unsorted_flist) {
2053                         flist->sorted = new_array(struct file_struct *, flist->used);
2054                         memcpy(flist->sorted, flist->files, flist->used * PTR_SIZE);
2055                 } else
2056                         flist->sorted = flist->files;
2057
2058                 flist_sort_and_clean(flist, 0);
2059
2060                 add_dirs_to_tree(send_dir_ndx, flist, stats.num_dirs - dstart);
2061                 flist_done_allocating(flist);
2062
2063                 file_total += flist->used;
2064                 stats.flist_size += stats.total_written - start_write;
2065                 stats.num_files += flist->used;
2066                 if (DEBUG_GTE(FLIST, 3))
2067                         output_flist(flist);
2068
2069                 if (DIR_FIRST_CHILD(dp) >= 0) {
2070                         send_dir_ndx = DIR_FIRST_CHILD(dp);
2071                         send_dir_depth++;
2072                 } else {
2073                         while (DIR_NEXT_SIBLING(dp) < 0) {
2074                                 if ((send_dir_ndx = DIR_PARENT(dp)) < 0) {
2075                                         write_ndx(f, NDX_FLIST_EOF);
2076                                         flist_eof = 1;
2077                                         if (DEBUG_GTE(FLIST, 3))
2078                                                 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2079                                         change_local_filter_dir(NULL, 0, 0);
2080                                         goto finish;
2081                                 }
2082                                 send_dir_depth--;
2083                                 file = dir_flist->sorted[send_dir_ndx];
2084                                 dp = F_DIR_NODE_P(file);
2085                         }
2086                         send_dir_ndx = DIR_NEXT_SIBLING(dp);
2087                 }
2088         }
2089
2090   finish:
2091         if (io_error != save_io_error && protocol_version == 30 && !ignore_errors)
2092                 send_msg_int(MSG_IO_ERROR, io_error);
2093 }
2094
2095 struct file_list *send_file_list(int f, int argc, char *argv[])
2096 {
2097         static const char *lastdir;
2098         static int lastdir_len = -1;
2099         int len, dirlen;
2100         STRUCT_STAT st;
2101         char *p, *dir;
2102         struct file_list *flist;
2103         struct timeval start_tv, end_tv;
2104         int64 start_write;
2105         int use_ff_fd = 0;
2106         int disable_buffering, reenable_multiplex = -1;
2107         int flags = recurse ? FLAG_CONTENT_DIR : 0;
2108         int reading_remotely = filesfrom_host != NULL;
2109         int rl_flags = (reading_remotely ? 0 : RL_DUMP_COMMENTS)
2110 #ifdef ICONV_OPTION
2111                      | (filesfrom_convert ? RL_CONVERT : 0)
2112 #endif
2113                      | (eol_nulls || reading_remotely ? RL_EOL_NULLS : 0);
2114         int implied_dot_dir = 0;
2115
2116         rprintf(FLOG, "building file list\n");
2117         if (show_filelist_progress)
2118                 start_filelist_progress("building file list");
2119         else if (inc_recurse && INFO_GTE(FLIST, 1) && !am_server)
2120                 rprintf(FCLIENT, "sending incremental file list\n");
2121
2122         start_write = stats.total_written;
2123         gettimeofday(&start_tv, NULL);
2124
2125         if (relative_paths && protocol_version >= 30)
2126                 implied_dirs = 1; /* We send flagged implied dirs */
2127
2128 #ifdef SUPPORT_HARD_LINKS
2129         if (preserve_hard_links && protocol_version >= 30 && !cur_flist)
2130                 init_hard_links();
2131 #endif
2132
2133         flist = cur_flist = flist_new(0, "send_file_list");
2134         if (inc_recurse) {
2135                 dir_flist = flist_new(FLIST_TEMP, "send_file_list");
2136                 flags |= FLAG_DIVERT_DIRS;
2137         } else
2138                 dir_flist = cur_flist;
2139
2140         disable_buffering = io_start_buffering_out(f);
2141         if (filesfrom_fd >= 0) {
2142                 if (argv[0] && !change_dir(argv[0], CD_NORMAL)) {
2143                         rsyserr(FERROR_XFER, errno, "change_dir %s failed",
2144                                 full_fname(argv[0]));
2145                         exit_cleanup(RERR_FILESELECT);
2146                 }
2147                 if (protocol_version < 31) {
2148                         /* Older protocols send the files-from data w/o packaging
2149                          * it in multiplexed I/O packets, so temporarily switch
2150                          * to buffered I/O to match this behavior. */
2151                         reenable_multiplex = io_end_multiplex_in(MPLX_TO_BUFFERED);
2152                 }
2153                 use_ff_fd = 1;
2154         }
2155
2156         if (!orig_dir)
2157                 orig_dir = strdup(curr_dir);
2158
2159         while (1) {
2160                 char fbuf[MAXPATHLEN], *fn, name_type;
2161
2162                 if (use_ff_fd) {
2163                         if (read_line(filesfrom_fd, fbuf, sizeof fbuf, rl_flags) == 0)
2164                                 break;
2165                         sanitize_path(fbuf, fbuf, "", 0, SP_KEEP_DOT_DIRS);
2166                 } else {
2167                         if (argc-- == 0)
2168                                 break;
2169                         strlcpy(fbuf, *argv++, MAXPATHLEN);
2170                         if (sanitize_paths)
2171                                 sanitize_path(fbuf, fbuf, "", 0, SP_KEEP_DOT_DIRS);
2172                 }
2173
2174                 len = strlen(fbuf);
2175                 if (relative_paths) {
2176                         /* We clean up fbuf below. */
2177                         name_type = NORMAL_NAME;
2178                 } else if (!len || fbuf[len - 1] == '/') {
2179                         if (len == 2 && fbuf[0] == '.') {
2180                                 /* Turn "./" into just "." rather than "./." */
2181                                 fbuf[--len] = '\0';
2182                         } else {
2183                                 if (len + 1 >= MAXPATHLEN)
2184                                         overflow_exit("send_file_list");
2185                                 fbuf[len++] = '.';
2186                                 fbuf[len] = '\0';
2187                         }
2188                         name_type = DOTDIR_NAME;
2189                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
2190                     && (len == 2 || fbuf[len-3] == '/')) {
2191                         if (len + 2 >= MAXPATHLEN)
2192                                 overflow_exit("send_file_list");
2193                         fbuf[len++] = '/';
2194                         fbuf[len++] = '.';
2195                         fbuf[len] = '\0';
2196                         name_type = DOTDIR_NAME;
2197                 } else if (fbuf[len-1] == '.' && (len == 1 || fbuf[len-2] == '/'))
2198                         name_type = DOTDIR_NAME;
2199                 else
2200                         name_type = NORMAL_NAME;
2201
2202                 dir = NULL;
2203
2204                 if (!relative_paths) {
2205                         p = strrchr(fbuf, '/');
2206                         if (p) {
2207                                 *p = '\0';
2208                                 if (p == fbuf)
2209                                         dir = "/";
2210                                 else
2211                                         dir = fbuf;
2212                                 len -= p - fbuf + 1;
2213                                 fn = p + 1;
2214                         } else
2215                                 fn = fbuf;
2216                 } else {
2217                         if ((p = strstr(fbuf, "/./")) != NULL) {
2218                                 *p = '\0';
2219                                 if (p == fbuf)
2220                                         dir = "/";
2221                                 else {
2222                                         dir = fbuf;
2223                                         clean_fname(dir, 0);
2224                                 }
2225                                 fn = p + 3;
2226                                 while (*fn == '/')
2227                                         fn++;
2228                                 if (!*fn)
2229                                         *--fn = '\0'; /* ensure room for '.' */
2230                         } else
2231                                 fn = fbuf;
2232                         /* A leading ./ can be used in relative mode to affect
2233                          * the dest dir without its name being in the path. */
2234                         if (*fn == '.' && fn[1] == '/' && fn[2] && !implied_dot_dir)
2235                                 implied_dot_dir = -1;
2236                         len = clean_fname(fn, CFN_KEEP_TRAILING_SLASH
2237                                             | CFN_DROP_TRAILING_DOT_DIR);
2238                         if (len == 1) {
2239                                 if (fn[0] == '/') {
2240                                         fn = "/.";
2241                                         len = 2;
2242                                         name_type = DOTDIR_NAME;
2243                                 } else if (fn[0] == '.')
2244                                         name_type = DOTDIR_NAME;
2245                         } else if (fn[len-1] == '/') {
2246                                 fn[--len] = '\0';
2247                                 if (len == 1 && *fn == '.')
2248                                         name_type = DOTDIR_NAME;
2249                                 else
2250                                         name_type = SLASH_ENDING_NAME;
2251                         }
2252                         /* Reject a ".." dir in the active part of the path. */
2253                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
2254                                 if ((p[2] == '/' || p[2] == '\0')
2255                                  && (p == fn || p[-1] == '/')) {
2256                                         rprintf(FERROR,
2257                                             "found \"..\" dir in relative path: %s\n",
2258                                             fn);
2259                                         exit_cleanup(RERR_SYNTAX);
2260                                 }
2261                         }
2262                 }
2263
2264                 if (!*fn) {
2265                         len = 1;
2266                         fn = ".";
2267                         name_type = DOTDIR_NAME;
2268                 }
2269
2270                 dirlen = dir ? strlen(dir) : 0;
2271                 if (dirlen != lastdir_len || memcmp(lastdir, dir, dirlen) != 0) {
2272                         if (!change_pathname(NULL, dir, -dirlen))
2273                                 goto bad_path;
2274                         lastdir = pathname;
2275                         lastdir_len = pathname_len;
2276                 } else if (!change_pathname(NULL, lastdir, lastdir_len)) {
2277                     bad_path:
2278                         if (implied_dot_dir < 0)
2279                                 implied_dot_dir = 0;
2280                         continue;
2281                 }
2282
2283                 if (implied_dot_dir < 0) {
2284                         implied_dot_dir = 1;
2285                         send_file_name(f, flist, ".", NULL, (flags | FLAG_IMPLIED_DIR) & ~FLAG_CONTENT_DIR, ALL_FILTERS);
2286                 }
2287
2288                 if (fn != fbuf)
2289                         memmove(fbuf, fn, len + 1);
2290
2291                 if (link_stat(fbuf, &st, copy_dirlinks || name_type != NORMAL_NAME) != 0
2292                  || (name_type != DOTDIR_NAME && is_excluded(fbuf, S_ISDIR(st.st_mode) != 0, SERVER_FILTERS))
2293                  || (relative_paths && path_is_daemon_excluded(fbuf, 1))) {
2294                         if (errno != ENOENT || missing_args == 0) {
2295                                 /* This is a transfer error, but inhibit deletion
2296                                  * only if we might be omitting an existing file. */
2297                                 if (errno != ENOENT)
2298                                         io_error |= IOERR_GENERAL;
2299                                 rsyserr(FERROR_XFER, errno, "link_stat %s failed",
2300                                         full_fname(fbuf));
2301                                 continue;
2302                         } else if (missing_args == 1) {
2303                                 /* Just ignore the arg. */
2304                                 continue;
2305                         } else /* (missing_args == 2) */ {
2306                                 /* Send the arg as a "missing" entry with
2307                                  * mode 0, which tells the generator to delete it. */
2308                                 memset(&st, 0, sizeof st);
2309                         }
2310                 }
2311
2312                 /* A dot-dir should not be excluded! */
2313                 if (name_type != DOTDIR_NAME && st.st_mode != 0
2314                  && is_excluded(fbuf, S_ISDIR(st.st_mode) != 0, ALL_FILTERS))
2315                         continue;
2316
2317                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
2318                         rprintf(FINFO, "skipping directory %s\n", fbuf);
2319                         continue;
2320                 }
2321
2322                 if (inc_recurse && relative_paths && *fbuf) {
2323                         if ((p = strchr(fbuf+1, '/')) != NULL) {
2324                                 if (p - fbuf == 1 && *fbuf == '.') {
2325                                         if ((fn = strchr(p+1, '/')) != NULL)
2326                                                 p = fn;
2327                                 } else
2328                                         fn = p;
2329                                 send_implied_dirs(f, flist, fbuf, fbuf, p, flags,
2330                                                   IS_MISSING_FILE(st) ? MISSING_NAME : name_type);
2331                                 if (fn == p)
2332                                         continue;
2333                         }
2334                 } else if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
2335                         /* Send the implied directories at the start of the
2336                          * source spec, so we get their permissions right. */
2337                         send_implied_dirs(f, flist, fbuf, fbuf, p, flags, 0);
2338                 }
2339
2340                 if (one_file_system)
2341                         filesystem_dev = st.st_dev;
2342
2343                 if (recurse || (xfer_dirs && name_type != NORMAL_NAME)) {
2344                         struct file_struct *file;
2345                         file = send_file_name(f, flist, fbuf, &st,
2346                                               FLAG_TOP_DIR | FLAG_CONTENT_DIR | flags,
2347                                               NO_FILTERS);
2348                         if (!file)
2349                                 continue;
2350                         if (inc_recurse) {
2351                                 if (name_type == DOTDIR_NAME) {
2352                                         if (send_dir_depth < 0) {
2353                                                 send_dir_depth = 0;
2354                                                 change_local_filter_dir(fbuf, len, send_dir_depth);
2355                                         }
2356                                         send_directory(f, flist, fbuf, len, flags);
2357                                 }
2358                         } else
2359                                 send_if_directory(f, flist, file, fbuf, len, flags);
2360                 } else
2361                         send_file_name(f, flist, fbuf, &st, flags, NO_FILTERS);
2362         }
2363
2364         if (reenable_multiplex >= 0)
2365                 io_start_multiplex_in(reenable_multiplex);
2366
2367         gettimeofday(&end_tv, NULL);
2368         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
2369                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
2370         if (stats.flist_buildtime == 0)
2371                 stats.flist_buildtime = 1;
2372         start_tv = end_tv;
2373
2374         /* Indicate end of file list */
2375         if (io_error == 0 || ignore_errors)
2376                 write_end_of_flist(f, 0);
2377         else if (use_safe_inc_flist)
2378                 write_end_of_flist(f, 1);
2379         else {
2380                 if (delete_during && inc_recurse)
2381                         fatal_unsafe_io_error();
2382                 write_end_of_flist(f, 0);
2383         }
2384
2385 #ifdef SUPPORT_HARD_LINKS
2386         if (preserve_hard_links && protocol_version >= 30 && !inc_recurse)
2387                 idev_destroy();
2388 #endif
2389
2390         if (show_filelist_progress)
2391                 finish_filelist_progress(flist);
2392
2393         gettimeofday(&end_tv, NULL);
2394         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
2395                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
2396
2397         /* When converting names, both sides keep an unsorted file-list array
2398          * because the names will differ on the sending and receiving sides
2399          * (both sides will use the unsorted index number for each item). */
2400
2401         /* Sort the list without removing any duplicates.  This allows the
2402          * receiving side to ask for whatever name it kept.  For incremental
2403          * recursion mode, the sender marks duplicate dirs so that it can
2404          * send them together in a single file-list. */
2405         if (need_unsorted_flist) {
2406                 flist->sorted = new_array(struct file_struct *, flist->used);
2407                 memcpy(flist->sorted, flist->files, flist->used * PTR_SIZE);
2408         } else
2409                 flist->sorted = flist->files;
2410         flist_sort_and_clean(flist, 0);
2411         file_total += flist->used;
2412         file_old_total += flist->used;
2413
2414         if (numeric_ids <= 0 && !inc_recurse)
2415                 send_id_lists(f);
2416
2417         /* send the io_error flag */
2418         if (protocol_version < 30)
2419                 write_int(f, ignore_errors ? 0 : io_error);
2420         else if (!use_safe_inc_flist && io_error && !ignore_errors)
2421                 send_msg_int(MSG_IO_ERROR, io_error);
2422
2423         if (disable_buffering)
2424                 io_end_buffering_out(IOBUF_FREE_BUFS);
2425
2426         stats.flist_size = stats.total_written - start_write;
2427         stats.num_files = flist->used;
2428
2429         if (DEBUG_GTE(FLIST, 3))
2430                 output_flist(flist);
2431
2432         if (DEBUG_GTE(FLIST, 2))
2433                 rprintf(FINFO, "send_file_list done\n");
2434
2435         if (inc_recurse) {
2436                 send_dir_depth = 1;
2437                 add_dirs_to_tree(-1, flist, stats.num_dirs);
2438                 if (!file_total || strcmp(flist->sorted[flist->low]->basename, ".") != 0)
2439                         flist->parent_ndx = -1;
2440                 flist_done_allocating(flist);
2441                 if (send_dir_ndx < 0) {
2442                         write_ndx(f, NDX_FLIST_EOF);
2443                         flist_eof = 1;
2444                         if (DEBUG_GTE(FLIST, 3))
2445                                 rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2446                 }
2447                 else if (file_total == 1) {
2448                         /* If we're creating incremental file-lists and there
2449                          * was just 1 item in the first file-list, send 1 more
2450                          * file-list to check if this is a 1-file xfer. */
2451                         send_extra_file_list(f, 1);
2452                 }
2453         } else {
2454                 flist_eof = 1;
2455                 if (DEBUG_GTE(FLIST, 3))
2456                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2457         }
2458
2459         return flist;
2460 }
2461
2462 struct file_list *recv_file_list(int f, int dir_ndx)
2463 {
2464         const char *good_dirname = NULL;
2465         struct file_list *flist;
2466         int dstart, flags;
2467         int64 start_read;
2468
2469         if (!first_flist) {
2470                 if (show_filelist_progress)
2471                         start_filelist_progress("receiving file list");
2472                 else if (inc_recurse && INFO_GTE(FLIST, 1) && !am_server)
2473                         rprintf(FCLIENT, "receiving incremental file list\n");
2474                 rprintf(FLOG, "receiving file list\n");
2475                 if (usermap)
2476                         parse_name_map(usermap, True);
2477                 if (groupmap)
2478                         parse_name_map(groupmap, False);
2479         }
2480
2481         start_read = stats.total_read;
2482
2483 #ifdef SUPPORT_HARD_LINKS
2484         if (preserve_hard_links && !first_flist)
2485                 init_hard_links();
2486 #endif
2487
2488         flist = flist_new(0, "recv_file_list");
2489
2490         if (inc_recurse) {
2491                 if (flist->ndx_start == 1)
2492                         dir_flist = flist_new(FLIST_TEMP, "recv_file_list");
2493                 dstart = dir_flist->used;
2494         } else {
2495                 dir_flist = flist;
2496                 dstart = 0;
2497         }
2498
2499         while (1) {
2500                 struct file_struct *file;
2501
2502                 if (xfer_flags_as_varint) {
2503                         if ((flags = read_varint(f)) == 0) {
2504                                 int err = read_varint(f);
2505                                 if (!ignore_errors)
2506                                         io_error |= err;
2507                                 break;
2508                         }
2509                 } else {
2510                         if ((flags = read_byte(f)) == 0)
2511                                 break;
2512
2513                         if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
2514                                 flags |= read_byte(f) << 8;
2515
2516                         if (flags == (XMIT_EXTENDED_FLAGS|XMIT_IO_ERROR_ENDLIST)) {
2517                                 int err;
2518                                 if (!use_safe_inc_flist) {
2519                                         rprintf(FERROR, "Invalid flist flag: %x\n", flags);
2520                                         exit_cleanup(RERR_PROTOCOL);
2521                                 }
2522                                 err = read_varint(f);
2523                                 if (!ignore_errors)
2524                                         io_error |= err;
2525                                 break;
2526                         }
2527                 }
2528
2529                 flist_expand(flist, 1);
2530                 file = recv_file_entry(f, flist, flags);
2531
2532                 if (inc_recurse) {
2533                         static const char empty_dir[] = "\0";
2534                         const char *cur_dir = file->dirname ? file->dirname : empty_dir;
2535                         if (relative_paths && *cur_dir == '/')
2536                                 cur_dir++;
2537                         if (cur_dir != good_dirname) {
2538                                 const char *d = dir_ndx >= 0 ? f_name(dir_flist->files[dir_ndx], NULL) : empty_dir;
2539                                 if (strcmp(cur_dir, d) != 0) {
2540                                         rprintf(FERROR,
2541                                                 "ABORTING due to invalid path from sender: %s/%s\n",
2542                                                 cur_dir, file->basename);
2543                                         exit_cleanup(RERR_PROTOCOL);
2544                                 }
2545                                 good_dirname = cur_dir;
2546                         }
2547                 }
2548
2549                 if (S_ISREG(file->mode)) {
2550                         /* Already counted */
2551                 } else if (S_ISDIR(file->mode)) {
2552                         if (inc_recurse) {
2553                                 flist_expand(dir_flist, 1);
2554                                 dir_flist->files[dir_flist->used++] = file;
2555                         }
2556                         stats.num_dirs++;
2557                 } else if (S_ISLNK(file->mode))
2558                         stats.num_symlinks++;
2559                 else if (IS_DEVICE(file->mode))
2560                         stats.num_symlinks++;
2561                 else
2562                         stats.num_specials++;
2563
2564                 flist->files[flist->used++] = file;
2565
2566                 maybe_emit_filelist_progress(flist->used);
2567
2568                 if (DEBUG_GTE(FLIST, 2)) {
2569                         char *name = f_name(file, NULL);
2570                         rprintf(FINFO, "recv_file_name(%s)\n", NS(name));
2571                 }
2572         }
2573         file_total += flist->used;
2574
2575         if (DEBUG_GTE(FLIST, 2))
2576                 rprintf(FINFO, "received %d names\n", flist->used);
2577
2578         if (show_filelist_progress)
2579                 finish_filelist_progress(flist);
2580
2581         if (need_unsorted_flist) {
2582                 /* Create an extra array of index pointers that we can sort for
2583                  * the generator's use (for wading through the files in sorted
2584                  * order and for calling flist_find()).  We keep the "files"
2585                  * list unsorted for our exchange of index numbers with the
2586                  * other side (since their names may not sort the same). */
2587                 flist->sorted = new_array(struct file_struct *, flist->used);
2588                 memcpy(flist->sorted, flist->files, flist->used * PTR_SIZE);
2589                 if (inc_recurse && dir_flist->used > dstart) {
2590                         static int dir_flist_malloced = 0;
2591                         if (dir_flist_malloced < dir_flist->malloced) {
2592                                 dir_flist->sorted = realloc_array(dir_flist->sorted,
2593                                                         struct file_struct *,
2594                                                         dir_flist->malloced);
2595                                 dir_flist_malloced = dir_flist->malloced;
2596                         }
2597                         memcpy(dir_flist->sorted + dstart, dir_flist->files + dstart,
2598                                (dir_flist->used - dstart) * PTR_SIZE);
2599                         fsort(dir_flist->sorted + dstart, dir_flist->used - dstart);
2600                 }
2601         } else {
2602                 flist->sorted = flist->files;
2603                 if (inc_recurse && dir_flist->used > dstart) {
2604                         dir_flist->sorted = dir_flist->files;
2605                         fsort(dir_flist->sorted + dstart, dir_flist->used - dstart);
2606                 }
2607         }
2608
2609         if (inc_recurse)
2610                 flist_done_allocating(flist);
2611         else if (f >= 0) {
2612                 recv_id_list(f, flist);
2613                 flist_eof = 1;
2614                 if (DEBUG_GTE(FLIST, 3))
2615                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2616         }
2617
2618         /* The --relative option sends paths with a leading slash, so we need
2619          * to specify the strip_root option here.  We rejected leading slashes
2620          * for a non-relative transfer in recv_file_entry(). */
2621         flist_sort_and_clean(flist, relative_paths);
2622
2623         if (protocol_version < 30) {
2624                 /* Recv the io_error flag */
2625                 int err = read_int(f);
2626                 if (!ignore_errors)
2627                         io_error |= err;
2628         } else if (inc_recurse && flist->ndx_start == 1) {
2629                 if (!file_total || strcmp(flist->sorted[flist->low]->basename, ".") != 0)
2630                         flist->parent_ndx = -1;
2631         }
2632
2633         if (DEBUG_GTE(FLIST, 3))
2634                 output_flist(flist);
2635
2636         if (DEBUG_GTE(FLIST, 2))
2637                 rprintf(FINFO, "recv_file_list done\n");
2638
2639         stats.flist_size += stats.total_read - start_read;
2640         stats.num_files += flist->used;
2641
2642         return flist;
2643 }
2644
2645 /* This is only used once by the receiver if the very first file-list
2646  * has exactly one item in it. */
2647 void recv_additional_file_list(int f)
2648 {
2649         struct file_list *flist;
2650         int ndx = read_ndx(f);
2651         if (ndx == NDX_FLIST_EOF) {
2652                 flist_eof = 1;
2653                 if (DEBUG_GTE(FLIST, 3))
2654                         rprintf(FINFO, "[%s] flist_eof=1\n", who_am_i());
2655                 change_local_filter_dir(NULL, 0, 0);
2656         } else {
2657                 ndx = NDX_FLIST_OFFSET - ndx;
2658                 if (ndx < 0 || ndx >= dir_flist->used) {
2659                         ndx = NDX_FLIST_OFFSET - ndx;
2660                         rprintf(FERROR,
2661                                 "[%s] Invalid dir index: %d (%d - %d)\n",
2662                                 who_am_i(), ndx, NDX_FLIST_OFFSET,
2663                                 NDX_FLIST_OFFSET - dir_flist->used + 1);
2664                         exit_cleanup(RERR_PROTOCOL);
2665                 }
2666                 if (DEBUG_GTE(FLIST, 3)) {
2667                         rprintf(FINFO, "[%s] receiving flist for dir %d\n",
2668                                 who_am_i(), ndx);
2669                 }
2670                 flist = recv_file_list(f, ndx);
2671                 flist->parent_ndx = ndx;
2672         }
2673 }
2674
2675 /* Search for an identically-named item in the file list.  Note that the
2676  * items must agree in their directory-ness, or no match is returned. */
2677 int flist_find(struct file_list *flist, struct file_struct *f)
2678 {
2679         int low = flist->low, high = flist->high;
2680         int diff, mid, mid_up;
2681
2682         while (low <= high) {
2683                 mid = (low + high) / 2;
2684                 if (F_IS_ACTIVE(flist->sorted[mid]))
2685                         mid_up = mid;
2686                 else {
2687                         /* Scan for the next non-empty entry using the cached
2688                          * distance values.  If the value isn't fully up-to-
2689                          * date, update it. */
2690                         mid_up = mid + F_DEPTH(flist->sorted[mid]);
2691                         if (!F_IS_ACTIVE(flist->sorted[mid_up])) {
2692                                 do {
2693                                     mid_up += F_DEPTH(flist->sorted[mid_up]);
2694                                 } while (!F_IS_ACTIVE(flist->sorted[mid_up]));
2695                                 F_DEPTH(flist->sorted[mid]) = mid_up - mid;
2696                         }
2697                         if (mid_up > high) {
2698                                 /* If there's nothing left above us, set high to
2699                                  * a non-empty entry below us and continue. */
2700                                 high = mid - (int)flist->sorted[mid]->len32;
2701                                 if (!F_IS_ACTIVE(flist->sorted[high])) {
2702                                         do {
2703                                             high -= (int)flist->sorted[high]->len32;
2704                                         } while (!F_IS_ACTIVE(flist->sorted[high]));
2705                                         flist->sorted[mid]->len32 = mid - high;
2706                                 }
2707                                 continue;
2708                         }
2709                 }
2710                 diff = f_name_cmp(flist->sorted[mid_up], f);
2711                 if (diff == 0) {
2712                         if (protocol_version < 29
2713                             && S_ISDIR(flist->sorted[mid_up]->mode)
2714                             != S_ISDIR(f->mode))
2715                                 return -1;
2716                         return mid_up;
2717                 }
2718                 if (diff < 0)
2719                         low = mid_up + 1;
2720                 else
2721                         high = mid - 1;
2722         }
2723         return -1;
2724 }
2725
2726 /* Search for a name in the file list.  You must specify want_dir_match as:
2727  * 1=match directories, 0=match non-directories, or -1=match either. */
2728 int flist_find_name(struct file_list *flist, const char *fname, int want_dir_match)
2729 {
2730         static struct file_struct *f;
2731         char fbuf[MAXPATHLEN];
2732         const char *slash = strrchr(fname, '/');
2733         const char *basename = slash ? slash+1 : fname;
2734
2735         if (!f)
2736                 f = (struct file_struct*)new_array(char, FILE_STRUCT_LEN + MAXPATHLEN + 1);
2737
2738         memset(f, 0, FILE_STRUCT_LEN);
2739         memcpy((void*)f->basename, basename, strlen(basename)+1);
2740
2741         if (slash) {
2742                 strlcpy(fbuf, fname, slash - fname + 1);
2743                 f->dirname = fbuf;
2744         } else
2745                 f->dirname = NULL;
2746
2747         f->mode = want_dir_match > 0 ? S_IFDIR : S_IFREG;
2748
2749         if (want_dir_match < 0)
2750                 return flist_find_ignore_dirness(flist, f);
2751         return flist_find(flist, f);
2752 }
2753
2754 /* Search for an identically-named item in the file list.  Differs from
2755  * flist_find in that an item that agrees with "f" in directory-ness is
2756  * preferred but one that does not is still found. */
2757 int flist_find_ignore_dirness(struct file_list *flist, struct file_struct *f)
2758 {
2759         mode_t save_mode;
2760         int ndx;
2761
2762         /* First look for an item that agrees in directory-ness. */
2763         ndx = flist_find(flist, f);
2764         if (ndx >= 0)
2765                 return ndx;
2766
2767         /* Temporarily flip f->mode to look for an item of opposite
2768          * directory-ness. */
2769         save_mode = f->mode;
2770         f->mode = S_ISDIR(f->mode) ? S_IFREG : S_IFDIR;
2771         ndx = flist_find(flist, f);
2772         f->mode = save_mode;
2773         return ndx;
2774 }
2775
2776 /*
2777  * Free up any resources a file_struct has allocated
2778  * and clear the file.
2779  */
2780 void clear_file(struct file_struct *file)
2781 {
2782         /* The +1 zeros out the first char of the basename. */
2783         memset(file, 0, FILE_STRUCT_LEN + 1);
2784         /* In an empty entry, F_DEPTH() is an offset to the next non-empty
2785          * entry.  Likewise for len32 in the opposite direction.  We assume
2786          * that we're alone for now since flist_find() will adjust the counts
2787          * it runs into that aren't up-to-date. */
2788         file->len32 = F_DEPTH(file) = 1;
2789 }
2790
2791 /* Allocate a new file list. */
2792 struct file_list *flist_new(int flags, char *msg)
2793 {
2794         struct file_list *flist;
2795
2796         flist = new0(struct file_list);
2797
2798         if (flags & FLIST_TEMP) {
2799                 if (!(flist->file_pool = pool_create(SMALL_EXTENT, 0,
2800                                                      out_of_memory,
2801                                                      POOL_INTERN)))
2802                         out_of_memory(msg);
2803         } else {
2804                 /* This is a doubly linked list with prev looping back to
2805                  * the end of the list, but the last next pointer is NULL. */
2806                 if (!first_flist) {
2807                         flist->file_pool = pool_create(NORMAL_EXTENT, 0,
2808                                                        out_of_memory,
2809                                                        POOL_INTERN);
2810                         if (!flist->file_pool)
2811                                 out_of_memory(msg);
2812
2813                         flist->ndx_start = flist->flist_num = inc_recurse ? 1 : 0;
2814
2815                         first_flist = cur_flist = flist->prev = flist;
2816                 } else {
2817                         struct file_list *prev = first_flist->prev;
2818
2819                         flist->file_pool = first_flist->file_pool;
2820
2821                         flist->ndx_start = prev->ndx_start + prev->used + 1;
2822                         flist->flist_num = prev->flist_num + 1;
2823
2824                         flist->prev = prev;
2825                         prev->next = first_flist->prev = flist;
2826                 }
2827                 flist->pool_boundary = pool_boundary(flist->file_pool, 0);
2828                 flist_cnt++;
2829         }
2830
2831         return flist;
2832 }
2833
2834 /* Free up all elements in a flist. */
2835 void flist_free(struct file_list *flist)
2836 {
2837         if (!flist->prev) {
2838                 /* Was FLIST_TEMP dir-list. */
2839         } else if (flist == flist->prev) {
2840                 first_flist = cur_flist = NULL;
2841                 file_total = 0;
2842                 flist_cnt = 0;
2843         } else {
2844                 if (flist == cur_flist)
2845                         cur_flist = flist->next;
2846                 if (flist == first_flist)
2847                         first_flist = first_flist->next;
2848                 else {
2849                         flist->prev->next = flist->next;
2850                         if (!flist->next)
2851                                 flist->next = first_flist;
2852                 }
2853                 flist->next->prev = flist->prev;
2854                 file_total -= flist->used;
2855                 flist_cnt--;
2856         }
2857
2858         if (!flist->prev || !flist_cnt)
2859                 pool_destroy(flist->file_pool);
2860         else
2861                 pool_free_old(flist->file_pool, flist->pool_boundary);
2862
2863         if (flist->sorted && flist->sorted != flist->files)
2864                 free(flist->sorted);
2865         free(flist->files);
2866         free(flist);
2867 }
2868
2869 /* This routine ensures we don't have any duplicate names in our file list.
2870  * duplicate names can cause corruption because of the pipelining. */
2871 static void flist_sort_and_clean(struct file_list *flist, int strip_root)
2872 {
2873         char fbuf[MAXPATHLEN];
2874         int i, prev_i;
2875
2876         if (!flist)
2877                 return;
2878         if (flist->used == 0) {
2879                 flist->high = -1;
2880                 flist->low = 0;
2881                 return;
2882         }
2883
2884         fsort(flist->sorted, flist->used);
2885
2886         if (!am_sender || inc_recurse) {
2887                 for (i = prev_i = 0; i < flist->used; i++) {
2888                         if (F_IS_ACTIVE(flist->sorted[i])) {
2889                                 prev_i = i;
2890                                 break;
2891                         }
2892                 }
2893                 flist->low = prev_i;
2894         } else {
2895                 i = prev_i = flist->used - 1;
2896                 flist->low = 0;
2897         }
2898
2899         while (++i < flist->used) {
2900                 int j;
2901                 struct file_struct *file = flist->sorted[i];
2902
2903                 if (!F_IS_ACTIVE(file))
2904                         continue;
2905                 if (f_name_cmp(file, flist->sorted[prev_i]) == 0)
2906                         j = prev_i;
2907                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
2908                         int save_mode = file->mode;
2909                         /* Make sure that this directory doesn't duplicate a
2910                          * non-directory earlier in the list. */
2911                         flist->high = prev_i;
2912                         file->mode = S_IFREG;
2913                         j = flist_find(flist, file);
2914                         file->mode = save_mode;
2915                 } else
2916                         j = -1;
2917                 if (j >= 0) {
2918                         int keep, drop;
2919                         /* If one is a dir and the other is not, we want to
2920                          * keep the dir because it might have contents in the
2921                          * list.  Otherwise keep the first one. */
2922                         if (S_ISDIR(file->mode)) {
2923                                 struct file_struct *fp = flist->sorted[j];
2924                                 if (!S_ISDIR(fp->mode))
2925                                         keep = i, drop = j;
2926                                 else {
2927                                         if (am_sender)
2928                                                 file->flags |= FLAG_DUPLICATE;
2929                                         else { /* Make sure we merge our vital flags. */
2930                                                 fp->flags |= file->flags & (FLAG_TOP_DIR|FLAG_CONTENT_DIR);
2931                                                 fp->flags &= file->flags | ~FLAG_IMPLIED_DIR;
2932                                         }
2933                                         keep = j, drop = i;
2934                                 }
2935                         } else
2936                                 keep = j, drop = i;
2937
2938                         if (!am_sender) {
2939                                 if (DEBUG_GTE(DUP, 1)) {
2940                                         rprintf(FINFO,
2941                                             "removing duplicate name %s from file list (%d)\n",
2942                                             f_name(file, fbuf), drop + flist->ndx_start);
2943                                 }
2944                                 clear_file(flist->sorted[drop]);
2945                         }
2946
2947                         if (keep == i) {
2948                                 if (flist->low == drop) {
2949                                         for (j = drop + 1;
2950                                              j < i && !F_IS_ACTIVE(flist->sorted[j]);
2951                                              j++) {}
2952                                         flist->low = j;
2953                                 }
2954                                 prev_i = i;
2955                         }
2956                 } else
2957                         prev_i = i;
2958         }
2959         flist->high = prev_i;
2960
2961         if (strip_root) {
2962                 /* We need to strip off the leading slashes for relative
2963                  * paths, but this must be done _after_ the sorting phase. */
2964                 for (i = flist->low; i <= flist->high; i++) {
2965                         struct file_struct *file = flist->sorted[i];
2966
2967                         if (!file->dirname)
2968                                 continue;
2969                         while (*file->dirname == '/')
2970                                 file->dirname++;
2971                         if (!*file->dirname)
2972                                 file->dirname = NULL;
2973                 }
2974         }
2975
2976         if (prune_empty_dirs && !am_sender) {
2977                 int j, prev_depth = 0;
2978
2979                 prev_i = 0; /* It's OK that this isn't really true. */
2980
2981                 for (i = flist->low; i <= flist->high; i++) {
2982                         struct file_struct *fp, *file = flist->sorted[i];
2983
2984                         /* This temporarily abuses the F_DEPTH() value for a
2985                          * directory that is in a chain that might get pruned.
2986                          * We restore the old value if it gets a reprieve. */
2987                         if (S_ISDIR(file->mode) && F_DEPTH(file)) {
2988                                 /* Dump empty dirs when coming back down. */
2989                                 for (j = prev_depth; j >= F_DEPTH(file); j--) {
2990                                         fp = flist->sorted[prev_i];
2991                                         if (F_DEPTH(fp) >= 0)
2992                                                 break;
2993                                         prev_i = -F_DEPTH(fp)-1;
2994                                         clear_file(fp);
2995                                 }
2996                                 prev_depth = F_DEPTH(file);
2997                                 if (is_excluded(f_name(file, fbuf), 1, ALL_FILTERS)) {
2998                                         /* Keep dirs through this dir. */
2999                                         for (j = prev_depth-1; ; j--) {
3000                                                 fp = flist->sorted[prev_i];
3001                                                 if (F_DEPTH(fp) >= 0)
3002                                                         break;
3003                                                 prev_i = -F_DEPTH(fp)-1;
3004                                                 F_DEPTH(fp) = j;
3005                                         }
3006                                 } else
3007                                         F_DEPTH(file) = -prev_i-1;
3008                                 prev_i = i;
3009                         } else {
3010                                 /* Keep dirs through this non-dir. */
3011                                 for (j = prev_depth; ; j--) {
3012                                         fp = flist->sorted[prev_i];
3013                                         if (F_DEPTH(fp) >= 0)
3014                                                 break;
3015                                         prev_i = -F_DEPTH(fp)-1;
3016                                         F_DEPTH(fp) = j;
3017                                 }
3018                         }
3019                 }
3020                 /* Dump all remaining empty dirs. */
3021                 while (1) {
3022                         struct file_struct *fp = flist->sorted[prev_i];
3023                         if (F_DEPTH(fp) >= 0)
3024                                 break;
3025                         prev_i = -F_DEPTH(fp)-1;
3026                         clear_file(fp);
3027                 }
3028
3029                 for (i = flist->low; i <= flist->high; i++) {
3030                         if (F_IS_ACTIVE(flist->sorted[i]))
3031                                 break;
3032                 }
3033                 flist->low = i;
3034                 for (i = flist->high; i >= flist->low; i--) {
3035                         if (F_IS_ACTIVE(flist->sorted[i]))
3036                                 break;
3037                 }
3038                 flist->high = i;
3039         }
3040 }
3041
3042 static void output_flist(struct file_list *flist)
3043 {
3044         char uidbuf[16], gidbuf[16], depthbuf[16];
3045         struct file_struct *file;
3046         const char *root, *dir, *slash, *name, *trail;
3047         const char *who = who_am_i();
3048         int i;
3049
3050         rprintf(FINFO, "[%s] flist start=%d, used=%d, low=%d, high=%d\n",
3051                 who, flist->ndx_start, flist->used, flist->low, flist->high);
3052         for (i = 0; i < flist->used; i++) {
3053                 file = flist->files[i];
3054                 if ((am_root || am_sender) && uid_ndx) {
3055                         snprintf(uidbuf, sizeof uidbuf, " uid=%u",
3056                                  F_OWNER(file));
3057                 } else
3058                         *uidbuf = '\0';
3059                 if (gid_ndx) {
3060                         static char parens[] = "(\0)\0\0\0";
3061                         char *pp = parens + (file->flags & FLAG_SKIP_GROUP ? 0 : 3);
3062                         snprintf(gidbuf, sizeof gidbuf, " gid=%s%u%s",
3063                                  pp, F_GROUP(file), pp + 2);
3064                 } else
3065                         *gidbuf = '\0';
3066                 if (!am_sender)
3067                         snprintf(depthbuf, sizeof depthbuf, "%d", F_DEPTH(file));
3068                 if (F_IS_ACTIVE(file)) {
3069                         root = am_sender ? NS(F_PATHNAME(file)) : depthbuf;
3070                         if ((dir = file->dirname) == NULL)
3071                                 dir = slash = "";
3072                         else
3073                                 slash = "/";
3074                         name = file->basename;
3075                         trail = S_ISDIR(file->mode) ? "/" : "";
3076                 } else
3077                         root = dir = slash = name = trail = "";
3078                 rprintf(FINFO,
3079                         "[%s] i=%d %s %s%s%s%s mode=0%o len=%s%s%s flags=%x\n",
3080                         who, i + flist->ndx_start,
3081                         root, dir, slash, name, trail,
3082                         (int)file->mode, comma_num(F_LENGTH(file)),
3083                         uidbuf, gidbuf, file->flags);
3084         }
3085 }
3086
3087 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
3088 enum fnc_type { t_PATH, t_ITEM };
3089
3090 static int found_prefix;
3091
3092 /* Compare the names of two file_struct entities, similar to how strcmp()
3093  * would do if it were operating on the joined strings.
3094  *
3095  * Some differences beginning with protocol_version 29: (1) directory names
3096  * are compared with an assumed trailing slash so that they compare in a
3097  * way that would cause them to sort immediately prior to any content they
3098  * may have; (2) a directory of any name compares after a non-directory of
3099  * any name at the same depth; (3) a directory with name "." compares prior
3100  * to anything else.  These changes mean that a directory and a non-dir
3101  * with the same name will not compare as equal (protocol_version >= 29).
3102  *
3103  * The dirname component can be an empty string, but the basename component
3104  * cannot (and never is in the current codebase).  The basename component
3105  * may be NULL (for a removed item), in which case it is considered to be
3106  * after any existing item. */
3107 int f_name_cmp(const struct file_struct *f1, const struct file_struct *f2)
3108 {
3109         int dif;
3110         const uchar *c1, *c2;
3111         enum fnc_state state1, state2;
3112         enum fnc_type type1, type2;
3113         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
3114
3115         if (!f1 || !F_IS_ACTIVE(f1)) {
3116                 if (!f2 || !F_IS_ACTIVE(f2))
3117                         return 0;
3118                 return -1;
3119         }
3120         if (!f2 || !F_IS_ACTIVE(f2))
3121                 return 1;
3122
3123         c1 = (uchar*)f1->dirname;
3124         c2 = (uchar*)f2->dirname;
3125         if (c1 == c2)
3126                 c1 = c2 = NULL;
3127         if (!c1) {
3128                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
3129                 c1 = (const uchar*)f1->basename;
3130                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
3131                         type1 = t_ITEM;
3132                         state1 = s_TRAILING;
3133                         c1 = (uchar*)"";
3134                 } else
3135                         state1 = s_BASE;
3136         } else {
3137                 type1 = t_path;
3138                 state1 = s_DIR;
3139         }
3140         if (!c2) {
3141                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
3142                 c2 = (const uchar*)f2->basename;
3143                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
3144                         type2 = t_ITEM;
3145                         state2 = s_TRAILING;
3146                         c2 = (uchar*)"";
3147                 } else
3148                         state2 = s_BASE;
3149         } else {
3150                 type2 = t_path;
3151                 state2 = s_DIR;
3152         }
3153
3154         if (type1 != type2)
3155                 return type1 == t_PATH ? 1 : -1;
3156
3157         do {
3158                 if (!*c1) {
3159                         switch (state1) {
3160                         case s_DIR:
3161                                 state1 = s_SLASH;
3162                                 c1 = (uchar*)"/";
3163                                 break;
3164                         case s_SLASH:
3165                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
3166                                 c1 = (const uchar*)f1->basename;
3167                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
3168                                         type1 = t_ITEM;
3169                                         state1 = s_TRAILING;
3170                                         c1 = (uchar*)"";
3171                                 } else
3172                                         state1 = s_BASE;
3173                                 break;
3174                         case s_BASE:
3175                                 state1 = s_TRAILING;
3176                                 if (type1 == t_PATH) {
3177                                         c1 = (uchar*)"/";
3178                                         break;
3179                                 }
3180                                 /* FALL THROUGH */
3181                         case s_TRAILING:
3182                                 type1 = t_ITEM;
3183                                 break;
3184                         }
3185                         if (*c2 && type1 != type2)
3186                                 return type1 == t_PATH ? 1 : -1;
3187                 }
3188                 if (!*c2) {
3189                         switch (state2) {
3190                         case s_DIR:
3191                                 state2 = s_SLASH;
3192                                 c2 = (uchar*)"/";
3193                                 break;
3194                         case s_SLASH:
3195                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
3196                                 c2 = (const uchar*)f2->basename;
3197                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
3198                                         type2 = t_ITEM;
3199                                         state2 = s_TRAILING;
3200                                         c2 = (uchar*)"";
3201                                 } else
3202                                         state2 = s_BASE;
3203                                 break;
3204                         case s_BASE:
3205                                 state2 = s_TRAILING;
3206                                 if (type2 == t_PATH) {
3207                                         c2 = (uchar*)"/";
3208                                         break;
3209                                 }
3210                                 /* FALL THROUGH */
3211                         case s_TRAILING:
3212                                 found_prefix = 1;
3213                                 if (!*c1)
3214                                         return 0;
3215                                 type2 = t_ITEM;
3216                                 break;
3217                         }
3218                         if (type1 != type2)
3219                                 return type1 == t_PATH ? 1 : -1;
3220                 }
3221         } while ((dif = (int)*c1++ - (int)*c2++) == 0);
3222
3223         return dif;
3224 }
3225
3226 /* Returns 1 if f1's filename has all of f2's filename as a prefix.  This does
3227  * not match if f2's basename is not an exact match of a path element in f1.
3228  * E.g. /path/foo is not a prefix of /path/foobar/baz, but /path/foobar is. */
3229 int f_name_has_prefix(const struct file_struct *f1, const struct file_struct *f2)
3230 {
3231         found_prefix = 0;
3232         f_name_cmp(f1, f2);
3233         return found_prefix;
3234 }
3235
3236 char *f_name_buf(void)
3237 {
3238         static char names[5][MAXPATHLEN];
3239         static unsigned int n;
3240
3241         n = (n + 1) % (sizeof names / sizeof names[0]);
3242
3243         return names[n];
3244 }
3245
3246 /* Return a copy of the full filename of a flist entry, using the indicated
3247  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
3248  * done because we checked the size when creating the file_struct entry.
3249  */
3250 char *f_name(const struct file_struct *f, char *fbuf)
3251 {
3252         if (!f || !F_IS_ACTIVE(f))
3253                 return NULL;
3254
3255         if (!fbuf)
3256                 fbuf = f_name_buf();
3257
3258         if (f->dirname) {
3259                 int len = strlen(f->dirname);
3260                 memcpy(fbuf, f->dirname, len);
3261                 fbuf[len] = '/';
3262                 strlcpy(fbuf + len + 1, f->basename, MAXPATHLEN - (len + 1));
3263         } else
3264                 strlcpy(fbuf, f->basename, MAXPATHLEN);
3265
3266         return fbuf;
3267 }
3268
3269 /* Do a non-recursive scan of the named directory, possibly ignoring all
3270  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
3271  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
3272  * buffer (the functions we call will append names onto the end, but the old
3273  * dir value will be restored on exit). */
3274 struct file_list *get_dirlist(char *dirname, int dlen, int flags)
3275 {
3276         struct file_list *dirlist;
3277         char dirbuf[MAXPATHLEN];
3278         int save_recurse = recurse;
3279         int save_xfer_dirs = xfer_dirs;
3280         int save_prune_empty_dirs = prune_empty_dirs;
3281         int senddir_fd = flags & GDL_IGNORE_FILTER_RULES ? -2 : -1;
3282         int senddir_flags = FLAG_CONTENT_DIR;
3283
3284         if (dlen < 0) {
3285                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
3286                 if (dlen >= MAXPATHLEN)
3287                         return NULL;
3288                 dirname = dirbuf;
3289         }
3290
3291         dirlist = flist_new(FLIST_TEMP, "get_dirlist");
3292
3293         if (flags & GDL_PERHAPS_DIR)
3294                 senddir_flags |= FLAG_PERHAPS_DIR;
3295
3296         recurse = 0;
3297         xfer_dirs = 1;
3298         send_directory(senddir_fd, dirlist, dirname, dlen, senddir_flags);
3299         xfer_dirs = save_xfer_dirs;
3300         recurse = save_recurse;
3301         if (INFO_GTE(PROGRESS, 1))
3302                 flist_count_offset += dirlist->used;
3303
3304         prune_empty_dirs = 0;
3305         dirlist->sorted = dirlist->files;
3306         flist_sort_and_clean(dirlist, 0);
3307         prune_empty_dirs = save_prune_empty_dirs;
3308
3309         if (DEBUG_GTE(FLIST, 3))
3310                 output_flist(dirlist);
3311
3312         return dirlist;
3313 }