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