Obey the new "munge symlinks" dameon setting.
[rsync/rsync.git] / flist.c
1 /*
2  * Generate and receive file lists.
3  *
4  * Copyright (C) 1996 Andrew Tridgell
5  * Copyright (C) 1996 Paul Mackerras
6  * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7  * Copyright (C) 2002, 2003, 2004, 2005, 2006 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 2 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, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA.
22  */
23
24 #include "rsync.h"
25
26 extern int verbose;
27 extern int list_only;
28 extern int am_root;
29 extern int am_server;
30 extern int am_daemon;
31 extern int am_sender;
32 extern int do_progress;
33 extern int always_checksum;
34 extern int module_id;
35 extern int ignore_errors;
36 extern int numeric_ids;
37 extern int recurse;
38 extern int xfer_dirs;
39 extern int filesfrom_fd;
40 extern int one_file_system;
41 extern int copy_dirlinks;
42 extern int keep_dirlinks;
43 extern int preserve_links;
44 extern int preserve_hard_links;
45 extern int preserve_devices;
46 extern int preserve_specials;
47 extern int preserve_uid;
48 extern int preserve_gid;
49 extern int relative_paths;
50 extern int implied_dirs;
51 extern int prune_empty_dirs;
52 extern int copy_links;
53 extern int copy_unsafe_links;
54 extern int protocol_version;
55 extern int sanitize_paths;
56 extern struct stats stats;
57 extern struct file_list *the_file_list;
58
59 extern char curr_dir[MAXPATHLEN];
60
61 extern struct chmod_mode_struct *chmod_modes;
62
63 extern struct filter_list_struct filter_list;
64 extern struct filter_list_struct server_filter_list;
65
66 int io_error;
67 int checksum_len;
68 dev_t filesystem_dev; /* used to implement -x */
69 unsigned int file_struct_len;
70
71 static char empty_sum[MD4_SUM_LENGTH];
72 static int flist_count_offset;
73
74 static void clean_flist(struct file_list *flist, int strip_root, int no_dups);
75 static void output_flist(struct file_list *flist);
76
77 void init_flist(void)
78 {
79         struct file_struct f;
80
81         /* Figure out how big the file_struct is without trailing padding */
82         file_struct_len = offsetof(struct file_struct, flags) + sizeof f.flags;
83         checksum_len = protocol_version < 21 ? 2 : MD4_SUM_LENGTH;
84 }
85
86 static int show_filelist_p(void)
87 {
88         return verbose && xfer_dirs && !am_server;
89 }
90
91 static void start_filelist_progress(char *kind)
92 {
93         rprintf(FCLIENT, "%s ... ", kind);
94         if (verbose > 1 || do_progress)
95                 rprintf(FCLIENT, "\n");
96         rflush(FINFO);
97 }
98
99 static void emit_filelist_progress(int count)
100 {
101         rprintf(FCLIENT, " %d files...\r", count);
102 }
103
104 static void maybe_emit_filelist_progress(int count)
105 {
106         if (do_progress && show_filelist_p() && (count % 100) == 0)
107                 emit_filelist_progress(count);
108 }
109
110 static void finish_filelist_progress(const struct file_list *flist)
111 {
112         if (do_progress) {
113                 /* This overwrites the progress line */
114                 rprintf(FINFO, "%d file%sto consider\n",
115                         flist->count, flist->count == 1 ? " " : "s ");
116         } else
117                 rprintf(FINFO, "done\n");
118 }
119
120 void show_flist_stats(void)
121 {
122         /* Nothing yet */
123 }
124
125 static void list_file_entry(struct file_struct *f)
126 {
127         char permbuf[PERMSTRING_SIZE];
128
129         if (!f->basename) {
130                 /* this can happen if duplicate names were removed */
131                 return;
132         }
133
134         permstring(permbuf, f->mode);
135
136 #ifdef SUPPORT_LINKS
137         if (preserve_links && S_ISLNK(f->mode)) {
138                 rprintf(FINFO, "%s %11.0f %s %s -> %s\n",
139                         permbuf,
140                         (double)f->length, timestring(f->modtime),
141                         f_name(f, NULL), f->u.link);
142         } else
143 #endif
144         {
145                 rprintf(FINFO, "%s %11.0f %s %s\n",
146                         permbuf,
147                         (double)f->length, timestring(f->modtime),
148                         f_name(f, NULL));
149         }
150 }
151
152 /* Stat either a symlink or its referent, depending on the settings of
153  * copy_links, copy_unsafe_links, etc.  Returns -1 on error, 0 on success.
154  *
155  * If path is the name of a symlink, then the linkbuf buffer (which must hold
156  * MAXPATHLEN chars) will be set to the symlink's target string.
157  *
158  * The stat structure pointed to by stp will contain information about the
159  * link or the referent as appropriate, if they exist. */
160 static int readlink_stat(const char *path, STRUCT_STAT *stp, char *linkbuf)
161 {
162 #ifdef SUPPORT_LINKS
163         if (link_stat(path, stp, copy_dirlinks) < 0)
164                 return -1;
165         if (S_ISLNK(stp->st_mode)) {
166                 int llen = readlink(path, linkbuf, MAXPATHLEN - 1);
167                 if (llen < 0)
168                         return -1;
169                 linkbuf[llen] = '\0';
170                 if (copy_unsafe_links && unsafe_symlink(linkbuf, path)) {
171                         if (verbose > 1) {
172                                 rprintf(FINFO,"copying unsafe symlink \"%s\" -> \"%s\"\n",
173                                         path, linkbuf);
174                         }
175                         return safe_stat(path, stp);
176                 }
177         }
178         return 0;
179 #else
180         return do_stat(path, stp);
181 #endif
182 }
183
184 int link_stat(const char *path, STRUCT_STAT *stp, int follow_dirlinks)
185 {
186 #ifdef SUPPORT_LINKS
187         if (copy_links)
188                 return safe_stat(path, stp);
189         if (do_lstat(path, stp) < 0)
190                 return -1;
191         if (follow_dirlinks && S_ISLNK(stp->st_mode)) {
192                 STRUCT_STAT st;
193                 if (safe_stat(path, &st) == 0 && S_ISDIR(st.st_mode))
194                         *stp = st;
195         }
196         return 0;
197 #else
198         return do_stat(path, stp);
199 #endif
200 }
201
202 /* This function is used to check if a file should be included/excluded
203  * from the list of files based on its name and type etc.  The value of
204  * filter_level is set to either SERVER_FILTERS or ALL_FILTERS. */
205 static int is_excluded(char *fname, int is_dir, int filter_level)
206 {
207 #if 0 /* This currently never happens, so avoid a useless compare. */
208         if (filter_level == NO_FILTERS)
209                 return 0;
210 #endif
211         if (fname) {
212                 /* never exclude '.', even if somebody does --exclude '*' */
213                 if (fname[0] == '.' && !fname[1])
214                         return 0;
215                 /* Handle the -R version of the '.' dir. */
216                 if (fname[0] == '/') {
217                         int len = strlen(fname);
218                         if (fname[len-1] == '.' && fname[len-2] == '/')
219                                 return 0;
220                 }
221         }
222         if (server_filter_list.head
223             && check_filter(&server_filter_list, fname, is_dir) < 0)
224                 return 1;
225         if (filter_level != ALL_FILTERS)
226                 return 0;
227         if (filter_list.head
228             && check_filter(&filter_list, fname, is_dir) < 0)
229                 return 1;
230         return 0;
231 }
232
233 static int to_wire_mode(mode_t mode)
234 {
235 #ifdef SUPPORT_LINKS
236         if (S_ISLNK(mode) && (_S_IFLNK != 0120000))
237                 return (mode & ~(_S_IFMT)) | 0120000;
238 #endif
239         return (int)mode;
240 }
241
242 static mode_t from_wire_mode(int mode)
243 {
244         if ((mode & (_S_IFMT)) == 0120000 && (_S_IFLNK != 0120000))
245                 return (mode & ~(_S_IFMT)) | _S_IFLNK;
246         return (mode_t)mode;
247 }
248
249 static void send_directory(int f, struct file_list *flist,
250                            char *fbuf, int len);
251
252 static char *flist_dir;
253 static int flist_dir_len;
254
255
256 /**
257  * Make sure @p flist is big enough to hold at least @p flist->count
258  * entries.
259  **/
260 void flist_expand(struct file_list *flist)
261 {
262         struct file_struct **new_ptr;
263
264         if (flist->count < flist->malloced)
265                 return;
266
267         if (flist->malloced < FLIST_START)
268                 flist->malloced = FLIST_START;
269         else if (flist->malloced >= FLIST_LINEAR)
270                 flist->malloced += FLIST_LINEAR;
271         else
272                 flist->malloced *= 2;
273
274         /*
275          * In case count jumped or we are starting the list
276          * with a known size just set it.
277          */
278         if (flist->malloced < flist->count)
279                 flist->malloced = flist->count;
280
281         new_ptr = realloc_array(flist->files, struct file_struct *,
282                                 flist->malloced);
283
284         if (verbose >= 2 && flist->malloced != FLIST_START) {
285                 rprintf(FCLIENT, "[%s] expand file_list to %.0f bytes, did%s move\n",
286                     who_am_i(),
287                     (double)sizeof flist->files[0] * flist->malloced,
288                     (new_ptr == flist->files) ? " not" : "");
289         }
290
291         flist->files = new_ptr;
292
293         if (!flist->files)
294                 out_of_memory("flist_expand");
295 }
296
297 static void send_file_entry(struct file_struct *file, int f)
298 {
299         unsigned short flags;
300         static time_t modtime;
301         static mode_t mode;
302         static int64 dev;
303         static dev_t rdev;
304         static uint32 rdev_major;
305         static uid_t uid;
306         static gid_t gid;
307         static char lastname[MAXPATHLEN];
308         char fname[MAXPATHLEN];
309         int l1, l2;
310
311         if (f < 0)
312                 return;
313
314         if (!file) {
315                 write_byte(f, 0);
316                 modtime = 0, mode = 0;
317                 dev = 0, rdev = makedev(0, 0);
318                 rdev_major = 0;
319                 uid = 0, gid = 0;
320                 *lastname = '\0';
321                 return;
322         }
323
324         f_name(file, fname);
325
326         flags = file->flags & XMIT_TOP_DIR;
327
328         if (file->mode == mode)
329                 flags |= XMIT_SAME_MODE;
330         else
331                 mode = file->mode;
332         if ((preserve_devices && IS_DEVICE(mode))
333          || (preserve_specials && IS_SPECIAL(mode))) {
334                 if (protocol_version < 28) {
335                         if (file->u.rdev == rdev)
336                                 flags |= XMIT_SAME_RDEV_pre28;
337                         else
338                                 rdev = file->u.rdev;
339                 } else {
340                         rdev = file->u.rdev;
341                         if ((uint32)major(rdev) == rdev_major)
342                                 flags |= XMIT_SAME_RDEV_MAJOR;
343                         else
344                                 rdev_major = major(rdev);
345                         if ((uint32)minor(rdev) <= 0xFFu)
346                                 flags |= XMIT_RDEV_MINOR_IS_SMALL;
347                 }
348         } else if (protocol_version < 28)
349                 rdev = makedev(0, 0);
350         if (file->uid == uid)
351                 flags |= XMIT_SAME_UID;
352         else
353                 uid = file->uid;
354         if (file->gid == gid)
355                 flags |= XMIT_SAME_GID;
356         else
357                 gid = file->gid;
358         if (file->modtime == modtime)
359                 flags |= XMIT_SAME_TIME;
360         else
361                 modtime = file->modtime;
362
363 #ifdef SUPPORT_HARD_LINKS
364         if (file->link_u.idev) {
365                 if (file->F_DEV == dev) {
366                         if (protocol_version >= 28)
367                                 flags |= XMIT_SAME_DEV;
368                 } else
369                         dev = file->F_DEV;
370                 flags |= XMIT_HAS_IDEV_DATA;
371         }
372 #endif
373
374         for (l1 = 0;
375             lastname[l1] && (fname[l1] == lastname[l1]) && (l1 < 255);
376             l1++) {}
377         l2 = strlen(fname+l1);
378
379         if (l1 > 0)
380                 flags |= XMIT_SAME_NAME;
381         if (l2 > 255)
382                 flags |= XMIT_LONG_NAME;
383
384         /* We must make sure we don't send a zero flag byte or the
385          * other end will terminate the flist transfer.  Note that
386          * the use of XMIT_TOP_DIR on a non-dir has no meaning, so
387          * it's harmless way to add a bit to the first flag byte. */
388         if (protocol_version >= 28) {
389                 if (!flags && !S_ISDIR(mode))
390                         flags |= XMIT_TOP_DIR;
391                 if ((flags & 0xFF00) || !flags) {
392                         flags |= XMIT_EXTENDED_FLAGS;
393                         write_byte(f, flags);
394                         write_byte(f, flags >> 8);
395                 } else
396                         write_byte(f, flags);
397         } else {
398                 if (!(flags & 0xFF))
399                         flags |= S_ISDIR(mode) ? XMIT_LONG_NAME : XMIT_TOP_DIR;
400                 write_byte(f, flags);
401         }
402         if (flags & XMIT_SAME_NAME)
403                 write_byte(f, l1);
404         if (flags & XMIT_LONG_NAME)
405                 write_int(f, l2);
406         else
407                 write_byte(f, l2);
408         write_buf(f, fname + l1, l2);
409
410         write_longint(f, file->length);
411         if (!(flags & XMIT_SAME_TIME))
412                 write_int(f, modtime);
413         if (!(flags & XMIT_SAME_MODE))
414                 write_int(f, to_wire_mode(mode));
415         if (preserve_uid && !(flags & XMIT_SAME_UID)) {
416                 if (!numeric_ids)
417                         add_uid(uid);
418                 write_int(f, uid);
419         }
420         if (preserve_gid && !(flags & XMIT_SAME_GID)) {
421                 if (!numeric_ids)
422                         add_gid(gid);
423                 write_int(f, gid);
424         }
425         if ((preserve_devices && IS_DEVICE(mode))
426          || (preserve_specials && IS_SPECIAL(mode))) {
427                 if (protocol_version < 28) {
428                         if (!(flags & XMIT_SAME_RDEV_pre28))
429                                 write_int(f, (int)rdev);
430                 } else {
431                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
432                                 write_int(f, major(rdev));
433                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
434                                 write_byte(f, minor(rdev));
435                         else
436                                 write_int(f, minor(rdev));
437                 }
438         }
439
440 #ifdef SUPPORT_LINKS
441         if (preserve_links && S_ISLNK(mode)) {
442                 int len = strlen(file->u.link);
443                 write_int(f, len);
444                 write_buf(f, file->u.link, len);
445         }
446 #endif
447
448 #ifdef SUPPORT_HARD_LINKS
449         if (flags & XMIT_HAS_IDEV_DATA) {
450                 if (protocol_version < 26) {
451                         /* 32-bit dev_t and ino_t */
452                         write_int(f, dev);
453                         write_int(f, file->F_INODE);
454                 } else {
455                         /* 64-bit dev_t and ino_t */
456                         if (!(flags & XMIT_SAME_DEV))
457                                 write_longint(f, dev);
458                         write_longint(f, file->F_INODE);
459                 }
460         }
461 #endif
462
463         if (always_checksum && (S_ISREG(mode) || protocol_version < 28)) {
464                 char *sum;
465                 if (S_ISREG(mode))
466                         sum = file->u.sum;
467                 else {
468                         /* Prior to 28, we sent a useless set of nulls. */
469                         sum = empty_sum;
470                 }
471                 write_buf(f, sum, checksum_len);
472         }
473
474         strlcpy(lastname, fname, MAXPATHLEN);
475 }
476
477 static struct file_struct *receive_file_entry(struct file_list *flist,
478                                               unsigned short flags, int f)
479 {
480         static time_t modtime;
481         static mode_t mode;
482         static int64 dev;
483         static dev_t rdev;
484         static uint32 rdev_major;
485         static uid_t uid;
486         static gid_t gid;
487         static char lastname[MAXPATHLEN], *lastdir;
488         static int lastdir_depth, lastdir_len = -1;
489         static unsigned int del_hier_name_len = 0;
490         static int in_del_hier = 0;
491         char thisname[MAXPATHLEN];
492         unsigned int l1 = 0, l2 = 0;
493         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
494         OFF_T file_length;
495         char *basename, *dirname, *bp;
496         struct file_struct *file;
497
498         if (!flist) {
499                 modtime = 0, mode = 0;
500                 dev = 0, rdev = makedev(0, 0);
501                 rdev_major = 0;
502                 uid = 0, gid = 0;
503                 *lastname = '\0';
504                 lastdir_len = -1;
505                 in_del_hier = 0;
506                 return NULL;
507         }
508
509         if (flags & XMIT_SAME_NAME)
510                 l1 = read_byte(f);
511
512         if (flags & XMIT_LONG_NAME)
513                 l2 = read_int(f);
514         else
515                 l2 = read_byte(f);
516
517         if (l2 >= MAXPATHLEN - l1) {
518                 rprintf(FERROR,
519                         "overflow: flags=0x%x l1=%d l2=%d lastname=%s\n",
520                         flags, l1, l2, lastname);
521                 overflow_exit("receive_file_entry");
522         }
523
524         strlcpy(thisname, lastname, l1 + 1);
525         read_sbuf(f, &thisname[l1], l2);
526         thisname[l1 + l2] = 0;
527
528         strlcpy(lastname, thisname, MAXPATHLEN);
529
530         clean_fname(thisname, 0);
531
532         if (sanitize_paths)
533                 sanitize_path(thisname, thisname, "", 0, NULL);
534
535         if ((basename = strrchr(thisname, '/')) != NULL) {
536                 dirname_len = ++basename - thisname; /* counts future '\0' */
537                 if (lastdir_len == dirname_len - 1
538                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
539                         dirname = lastdir;
540                         dirname_len = 0; /* indicates no copy is needed */
541                 } else
542                         dirname = thisname;
543         } else {
544                 basename = thisname;
545                 dirname = NULL;
546                 dirname_len = 0;
547         }
548         basename_len = strlen(basename) + 1; /* count the '\0' */
549
550         file_length = read_longint(f);
551         if (!(flags & XMIT_SAME_TIME))
552                 modtime = (time_t)read_int(f);
553         if (!(flags & XMIT_SAME_MODE))
554                 mode = from_wire_mode(read_int(f));
555
556         if (chmod_modes && !S_ISLNK(mode))
557                 mode = tweak_mode(mode, chmod_modes);
558
559         if (preserve_uid && !(flags & XMIT_SAME_UID))
560                 uid = (uid_t)read_int(f);
561         if (preserve_gid && !(flags & XMIT_SAME_GID))
562                 gid = (gid_t)read_int(f);
563
564         if ((preserve_devices && IS_DEVICE(mode))
565          || (preserve_specials && IS_SPECIAL(mode))) {
566                 if (protocol_version < 28) {
567                         if (!(flags & XMIT_SAME_RDEV_pre28))
568                                 rdev = (dev_t)read_int(f);
569                 } else {
570                         uint32 rdev_minor;
571                         if (!(flags & XMIT_SAME_RDEV_MAJOR))
572                                 rdev_major = read_int(f);
573                         if (flags & XMIT_RDEV_MINOR_IS_SMALL)
574                                 rdev_minor = read_byte(f);
575                         else
576                                 rdev_minor = read_int(f);
577                         rdev = makedev(rdev_major, rdev_minor);
578                 }
579         } else if (protocol_version < 28)
580                 rdev = makedev(0, 0);
581
582 #ifdef SUPPORT_LINKS
583         if (preserve_links && S_ISLNK(mode)) {
584                 linkname_len = read_int(f) + 1; /* count the '\0' */
585                 if (linkname_len <= 0 || linkname_len > MAXPATHLEN) {
586                         rprintf(FERROR, "overflow: linkname_len=%d\n",
587                                 linkname_len - 1);
588                         overflow_exit("receive_file_entry");
589                 }
590         }
591         else
592 #endif
593                 linkname_len = 0;
594
595         sum_len = always_checksum && S_ISREG(mode) ? MD4_SUM_LENGTH : 0;
596
597         alloc_len = file_struct_len + dirname_len + basename_len
598                   + linkname_len + sum_len;
599         bp = pool_alloc(flist->file_pool, alloc_len, "receive_file_entry");
600
601         file = (struct file_struct *)bp;
602         memset(bp, 0, file_struct_len);
603         bp += file_struct_len;
604
605         file->modtime = modtime;
606         file->length = file_length;
607         file->mode = mode;
608         file->uid = uid;
609         file->gid = gid;
610
611         if (dirname_len) {
612                 file->dirname = lastdir = bp;
613                 lastdir_len = dirname_len - 1;
614                 memcpy(bp, dirname, dirname_len - 1);
615                 bp += dirname_len;
616                 bp[-1] = '\0';
617                 lastdir_depth = count_dir_elements(lastdir);
618                 file->dir.depth = lastdir_depth + 1;
619         } else if (dirname) {
620                 file->dirname = dirname; /* we're reusing lastname */
621                 file->dir.depth = lastdir_depth + 1;
622         } else
623                 file->dir.depth = 1;
624
625         if (S_ISDIR(mode)) {
626                 if (basename_len == 1+1 && *basename == '.') /* +1 for '\0' */
627                         file->dir.depth--;
628                 if (flags & XMIT_TOP_DIR) {
629                         in_del_hier = recurse;
630                         del_hier_name_len = file->dir.depth == 0 ? 0 : l1 + l2;
631                         if (relative_paths && del_hier_name_len > 2
632                             && lastname[del_hier_name_len-1] == '.'
633                             && lastname[del_hier_name_len-2] == '/')
634                                 del_hier_name_len -= 2;
635                         file->flags |= FLAG_TOP_DIR | FLAG_DEL_HERE;
636                 } else if (in_del_hier) {
637                         if (!relative_paths || !del_hier_name_len
638                          || (l1 >= del_hier_name_len
639                           && lastname[del_hier_name_len] == '/'))
640                                 file->flags |= FLAG_DEL_HERE;
641                         else
642                                 in_del_hier = 0;
643                 }
644         }
645
646         file->basename = bp;
647         memcpy(bp, basename, basename_len);
648         bp += basename_len;
649
650         if ((preserve_devices && IS_DEVICE(mode))
651          || (preserve_specials && IS_SPECIAL(mode)))
652                 file->u.rdev = rdev;
653
654 #ifdef SUPPORT_LINKS
655         if (linkname_len) {
656                 file->u.link = bp;
657                 read_sbuf(f, bp, linkname_len - 1);
658                 if (lp_munge_symlinks(module_id))
659                         sanitize_path(bp, bp, "", lastdir_depth, NULL);
660                 bp += linkname_len;
661         }
662 #endif
663
664 #ifdef SUPPORT_HARD_LINKS
665         if (preserve_hard_links && protocol_version < 28 && S_ISREG(mode))
666                 flags |= XMIT_HAS_IDEV_DATA;
667         if (flags & XMIT_HAS_IDEV_DATA) {
668                 int64 inode;
669                 if (protocol_version < 26) {
670                         dev = read_int(f);
671                         inode = read_int(f);
672                 } else {
673                         if (!(flags & XMIT_SAME_DEV))
674                                 dev = read_longint(f);
675                         inode = read_longint(f);
676                 }
677                 if (flist->hlink_pool) {
678                         file->link_u.idev = pool_talloc(flist->hlink_pool,
679                             struct idev, 1, "inode_table");
680                         file->F_INODE = inode;
681                         file->F_DEV = dev;
682                 }
683         }
684 #endif
685
686         if (always_checksum && (sum_len || protocol_version < 28)) {
687                 char *sum;
688                 if (sum_len) {
689                         file->u.sum = sum = bp;
690                         /*bp += sum_len;*/
691                 } else {
692                         /* Prior to 28, we get a useless set of nulls. */
693                         sum = empty_sum;
694                 }
695                 read_buf(f, sum, checksum_len);
696         }
697
698         return file;
699 }
700
701 /**
702  * Create a file_struct for a named file by reading its stat()
703  * information and performing extensive checks against global
704  * options.
705  *
706  * @return the new file, or NULL if there was an error or this file
707  * should be excluded.
708  *
709  * @todo There is a small optimization opportunity here to avoid
710  * stat()ing the file in some circumstances, which has a certain cost.
711  * We are called immediately after doing readdir(), and so we may
712  * already know the d_type of the file.  We could for example avoid
713  * statting directories if we're not recursing, but this is not a very
714  * important case.  Some systems may not have d_type.
715  **/
716 struct file_struct *make_file(char *fname, struct file_list *flist,
717                               STRUCT_STAT *stp, unsigned short flags,
718                               int filter_level)
719 {
720         static char *lastdir;
721         static int lastdir_len = -1;
722         struct file_struct *file;
723         STRUCT_STAT st;
724         char sum[SUM_LENGTH];
725         char thisname[MAXPATHLEN];
726         char linkname[MAXPATHLEN];
727         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
728         char *basename, *dirname, *bp;
729
730         if (!flist || !flist->count)    /* Ignore lastdir when invalid. */
731                 lastdir_len = -1;
732
733         if (strlcpy(thisname, fname, sizeof thisname)
734             >= sizeof thisname - flist_dir_len) {
735                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
736                 return NULL;
737         }
738         clean_fname(thisname, 0);
739         if (sanitize_paths)
740                 sanitize_path(thisname, thisname, "", 0, NULL);
741
742         memset(sum, 0, SUM_LENGTH);
743
744         if (stp && S_ISDIR(stp->st_mode))
745                 st = *stp; /* Needed for "symlink/." with --relative. */
746         else if (readlink_stat(thisname, &st, linkname) != 0) {
747                 int save_errno = errno;
748                 /* See if file is excluded before reporting an error. */
749                 if (filter_level != NO_FILTERS
750                     && is_excluded(thisname, 0, filter_level))
751                         return NULL;
752                 if (save_errno == ENOENT) {
753 #ifdef SUPPORT_LINKS
754                         /* Avoid "vanished" error if symlink points nowhere. */
755                         if (copy_links && do_lstat(thisname, &st) == 0
756                             && S_ISLNK(st.st_mode)) {
757                                 io_error |= IOERR_GENERAL;
758                                 rprintf(FERROR, "symlink has no referent: %s\n",
759                                         full_fname(thisname));
760                         } else
761 #endif
762                         {
763                                 enum logcode c = am_daemon && protocol_version < 28
764                                     ? FERROR : FINFO;
765                                 io_error |= IOERR_VANISHED;
766                                 rprintf(c, "file has vanished: %s\n",
767                                         full_fname(thisname));
768                         }
769                 } else {
770                         io_error |= IOERR_GENERAL;
771                         rsyserr(FERROR, save_errno, "readlink %s failed",
772                                 full_fname(thisname));
773                 }
774                 return NULL;
775         }
776
777         /* backup.c calls us with filter_level set to NO_FILTERS. */
778         if (filter_level == NO_FILTERS)
779                 goto skip_filters;
780
781         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
782                 rprintf(FINFO, "skipping directory %s\n", thisname);
783                 return NULL;
784         }
785
786         /* We only care about directories because we need to avoid recursing
787          * into a mount-point directory, not to avoid copying a symlinked
788          * file if -L (or similar) was specified. */
789         if (one_file_system && st.st_dev != filesystem_dev
790          && S_ISDIR(st.st_mode)) {
791                 if (one_file_system > 1) {
792                         if (verbose > 2) {
793                                 rprintf(FINFO, "skipping mount-point dir %s\n",
794                                         thisname);
795                         }
796                         return NULL;
797                 }
798                 flags |= FLAG_MOUNT_POINT;
799         }
800
801         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level))
802                 return NULL;
803
804         if (lp_ignore_nonreadable(module_id)) {
805 #ifdef SUPPORT_LINKS
806                 if (!S_ISLNK(st.st_mode))
807 #endif
808                         if (access(thisname, R_OK) != 0)
809                                 return NULL;
810         }
811
812   skip_filters:
813
814         if (verbose > 2) {
815                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
816                         who_am_i(), thisname, filter_level);
817         }
818
819         if ((basename = strrchr(thisname, '/')) != NULL) {
820                 dirname_len = ++basename - thisname; /* counts future '\0' */
821                 if (lastdir_len == dirname_len - 1
822                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
823                         dirname = lastdir;
824                         dirname_len = 0; /* indicates no copy is needed */
825                 } else
826                         dirname = thisname;
827         } else {
828                 basename = thisname;
829                 dirname = NULL;
830                 dirname_len = 0;
831         }
832         basename_len = strlen(basename) + 1; /* count the '\0' */
833
834 #ifdef SUPPORT_LINKS
835         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
836 #else
837         linkname_len = 0;
838 #endif
839
840         sum_len = always_checksum && am_sender && S_ISREG(st.st_mode)
841                 ? MD4_SUM_LENGTH : 0;
842
843         alloc_len = file_struct_len + dirname_len + basename_len
844                   + linkname_len + sum_len;
845         if (flist)
846                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
847         else {
848                 if (!(bp = new_array(char, alloc_len)))
849                         out_of_memory("make_file");
850         }
851
852         file = (struct file_struct *)bp;
853         memset(bp, 0, file_struct_len);
854         bp += file_struct_len;
855
856         file->flags = flags;
857         file->modtime = st.st_mtime;
858         file->length = st.st_size;
859         file->mode = st.st_mode;
860         file->uid = st.st_uid;
861         file->gid = st.st_gid;
862
863 #ifdef SUPPORT_HARD_LINKS
864         if (flist && flist->hlink_pool) {
865                 if (protocol_version < 28) {
866                         if (S_ISREG(st.st_mode))
867                                 file->link_u.idev = pool_talloc(
868                                     flist->hlink_pool, struct idev, 1,
869                                     "inode_table");
870                 } else {
871                         if (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
872                                 file->link_u.idev = pool_talloc(
873                                     flist->hlink_pool, struct idev, 1,
874                                     "inode_table");
875                 }
876         }
877         if (file->link_u.idev) {
878                 file->F_DEV = st.st_dev;
879                 file->F_INODE = st.st_ino;
880         }
881 #endif
882
883         if (dirname_len) {
884                 file->dirname = lastdir = bp;
885                 lastdir_len = dirname_len - 1;
886                 memcpy(bp, dirname, dirname_len - 1);
887                 bp += dirname_len;
888                 bp[-1] = '\0';
889         } else if (dirname)
890                 file->dirname = dirname;
891
892         file->basename = bp;
893         memcpy(bp, basename, basename_len);
894         bp += basename_len;
895
896 #ifdef HAVE_STRUCT_STAT_ST_RDEV
897         if ((preserve_devices && IS_DEVICE(st.st_mode))
898          || (preserve_specials && IS_SPECIAL(st.st_mode)))
899                 file->u.rdev = st.st_rdev;
900 #endif
901
902 #ifdef SUPPORT_LINKS
903         if (linkname_len) {
904                 file->u.link = bp;
905                 memcpy(bp, linkname, linkname_len);
906                 bp += linkname_len;
907         }
908 #endif
909
910         if (sum_len) {
911                 file->u.sum = bp;
912                 file_checksum(thisname, bp, st.st_size);
913                 /*bp += sum_len;*/
914         }
915
916         file->dir.root = flist_dir;
917
918         /* This code is only used by the receiver when it is building
919          * a list of files for a delete pass. */
920         if (keep_dirlinks && linkname_len && flist) {
921                 STRUCT_STAT st2;
922                 int save_mode = file->mode;
923                 file->mode = S_IFDIR; /* Find a directory with our name. */
924                 if (flist_find(the_file_list, file) >= 0
925                     && safe_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
926                         file->modtime = st2.st_mtime;
927                         file->length = st2.st_size;
928                         file->mode = st2.st_mode;
929                         file->uid = st2.st_uid;
930                         file->gid = st2.st_gid;
931                         file->u.link = NULL;
932                 } else
933                         file->mode = save_mode;
934         }
935
936         if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
937                 stats.total_size += st.st_size;
938
939         return file;
940 }
941
942 static struct file_struct *send_file_name(int f, struct file_list *flist,
943                                           char *fname, STRUCT_STAT *stp,
944                                           unsigned short flags)
945 {
946         struct file_struct *file;
947
948         file = make_file(fname, flist, stp, flags,
949                          f == -2 ? SERVER_FILTERS : ALL_FILTERS);
950         if (!file)
951                 return NULL;
952
953         if (chmod_modes && !S_ISLNK(file->mode))
954                 file->mode = tweak_mode(file->mode, chmod_modes);
955
956         maybe_emit_filelist_progress(flist->count + flist_count_offset);
957
958         flist_expand(flist);
959
960         if (file->basename[0]) {
961                 flist->files[flist->count++] = file;
962                 send_file_entry(file, f);
963         }
964         return file;
965 }
966
967 static void send_if_directory(int f, struct file_list *flist,
968                               struct file_struct *file,
969                               char *fbuf, unsigned int ol)
970 {
971         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
972
973         if (S_ISDIR(file->mode)
974             && !(file->flags & FLAG_MOUNT_POINT) && f_name(file, fbuf)) {
975                 void *save_filters;
976                 unsigned int len = strlen(fbuf);
977                 if (len > 1 && fbuf[len-1] == '/')
978                         fbuf[--len] = '\0';
979                 if (len >= MAXPATHLEN - 1) {
980                         io_error |= IOERR_GENERAL;
981                         rprintf(FERROR, "skipping long-named directory: %s\n",
982                                 full_fname(fbuf));
983                         return;
984                 }
985                 save_filters = push_local_filters(fbuf, len);
986                 send_directory(f, flist, fbuf, len);
987                 pop_local_filters(save_filters);
988                 fbuf[ol] = '\0';
989                 if (is_dot_dir)
990                         fbuf[ol-1] = '.';
991         }
992 }
993
994 /* This function is normally called by the sender, but the receiving side also
995  * calls it from get_dirlist() with f set to -1 so that we just construct the
996  * file list in memory without sending it over the wire.  Also, get_dirlist()
997  * might call this with f set to -2, which also indicates that local filter
998  * rules should be ignored. */
999 static void send_directory(int f, struct file_list *flist,
1000                            char *fbuf, int len)
1001 {
1002         struct dirent *di;
1003         unsigned remainder;
1004         char *p;
1005         DIR *d;
1006         int start = flist->count;
1007
1008         if (!(d = opendir(fbuf))) {
1009                 io_error |= IOERR_GENERAL;
1010                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1011                 return;
1012         }
1013
1014         p = fbuf + len;
1015         if (len != 1 || *fbuf != '/')
1016                 *p++ = '/';
1017         *p = '\0';
1018         remainder = MAXPATHLEN - (p - fbuf);
1019
1020         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1021                 char *dname = d_name(di);
1022                 if (dname[0] == '.' && (dname[1] == '\0'
1023                     || (dname[1] == '.' && dname[2] == '\0')))
1024                         continue;
1025                 if (strlcpy(p, dname, remainder) >= remainder) {
1026                         io_error |= IOERR_GENERAL;
1027                         rprintf(FINFO,
1028                                 "cannot send long-named file %s\n",
1029                                 full_fname(fbuf));
1030                         continue;
1031                 }
1032
1033                 send_file_name(f, flist, fbuf, NULL, 0);
1034         }
1035
1036         fbuf[len] = '\0';
1037
1038         if (errno) {
1039                 io_error |= IOERR_GENERAL;
1040                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1041         }
1042
1043         closedir(d);
1044
1045         if (recurse) {
1046                 int i, end = flist->count - 1;
1047                 for (i = start; i <= end; i++)
1048                         send_if_directory(f, flist, flist->files[i], fbuf, len);
1049         }
1050 }
1051
1052 struct file_list *send_file_list(int f, int argc, char *argv[])
1053 {
1054         int len;
1055         STRUCT_STAT st;
1056         char *p, *dir, olddir[sizeof curr_dir];
1057         char lastpath[MAXPATHLEN] = "";
1058         struct file_list *flist;
1059         struct timeval start_tv, end_tv;
1060         int64 start_write;
1061         int use_ff_fd = 0;
1062
1063         rprintf(FLOG, "building file list\n");
1064         if (show_filelist_p())
1065                 start_filelist_progress("building file list");
1066
1067         start_write = stats.total_written;
1068         gettimeofday(&start_tv, NULL);
1069
1070         flist = flist_new(WITH_HLINK, "send_file_list");
1071
1072         io_start_buffering_out();
1073         if (filesfrom_fd >= 0) {
1074                 if (sanitize_paths)
1075                         die_on_unsafe_path(argv[0], 0);
1076                 if (argv[0] && !push_dir(argv[0])) {
1077                         rsyserr(FERROR, errno, "push_dir %s failed",
1078                                 full_fname(argv[0]));
1079                         exit_cleanup(RERR_FILESELECT);
1080                 }
1081                 use_ff_fd = 1;
1082         }
1083
1084         while (1) {
1085                 char fbuf[MAXPATHLEN];
1086                 char *fn;
1087                 int is_dot_dir;
1088
1089                 if (use_ff_fd) {
1090                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1091                                 break;
1092                         sanitize_path(fbuf, fbuf, "", 0, NULL);
1093                 } else {
1094                         if (argc-- == 0)
1095                                 break;
1096                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1097                         if (sanitize_paths)
1098                                 sanitize_path(fbuf, fbuf, "", 0, NULL);
1099                 }
1100
1101                 len = strlen(fbuf);
1102                 if (relative_paths) {
1103                         /* We clean up fbuf below. */
1104                         is_dot_dir = 0;
1105                 } else if (!len || fbuf[len - 1] == '/') {
1106                         if (len == 2 && fbuf[0] == '.') {
1107                                 /* Turn "./" into just "." rather than "./." */
1108                                 fbuf[1] = '\0';
1109                         } else {
1110                                 if (len + 1 >= MAXPATHLEN)
1111                                         overflow_exit("send_file_list");
1112                                 fbuf[len++] = '.';
1113                                 fbuf[len] = '\0';
1114                         }
1115                         is_dot_dir = 1;
1116                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1117                     && (len == 2 || fbuf[len-3] == '/')) {
1118                         if (len + 2 >= MAXPATHLEN)
1119                                 overflow_exit("send_file_list");
1120                         fbuf[len++] = '/';
1121                         fbuf[len++] = '.';
1122                         fbuf[len] = '\0';
1123                         is_dot_dir = 1;
1124                 } else {
1125                         is_dot_dir = fbuf[len-1] == '.'
1126                                    && (len == 1 || fbuf[len-2] == '/');
1127                 }
1128
1129                 if (sanitize_paths)
1130                         die_on_unsafe_path(fbuf, 1);
1131                 if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
1132                         io_error |= IOERR_GENERAL;
1133                         rsyserr(FERROR, errno, "link_stat %s failed",
1134                                 full_fname(fbuf));
1135                         continue;
1136                 }
1137
1138                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1139                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1140                         continue;
1141                 }
1142
1143                 dir = NULL;
1144                 olddir[0] = '\0';
1145
1146                 if (!relative_paths) {
1147                         p = strrchr(fbuf, '/');
1148                         if (p) {
1149                                 *p = '\0';
1150                                 if (p == fbuf)
1151                                         dir = "/";
1152                                 else
1153                                         dir = fbuf;
1154                                 len -= p - fbuf + 1;
1155                                 fn = p + 1;
1156                         } else
1157                                 fn = fbuf;
1158                 } else {
1159                         if ((p = strstr(fbuf, "/./")) != NULL) {
1160                                 *p = '\0';
1161                                 if (p == fbuf)
1162                                         dir = "/";
1163                                 else
1164                                         dir = fbuf;
1165                                 len -= p - fbuf + 3;
1166                                 fn = p + 3;
1167                         } else
1168                                 fn = fbuf;
1169                         /* Get rid of trailing "/" and "/.". */
1170                         while (len) {
1171                                 if (fn[len - 1] == '/') {
1172                                         is_dot_dir = 1;
1173                                         if (!--len && !dir) {
1174                                                 len++;
1175                                                 break;
1176                                         }
1177                                 }
1178                                 else if (len >= 2 && fn[len - 1] == '.'
1179                                                   && fn[len - 2] == '/') {
1180                                         is_dot_dir = 1;
1181                                         if (!(len -= 2) && !dir) {
1182                                                 len++;
1183                                                 break;
1184                                         }
1185                                 } else
1186                                         break;
1187                         }
1188                         fn[len] = '\0';
1189                         /* Reject a ".." dir in the active part of the path. */
1190                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1191                                 if ((p[2] == '/' || p[2] == '\0')
1192                                  && (p == fn || p[-1] == '/')) {
1193                                         rprintf(FERROR,
1194                                             "found \"..\" dir in relative path: %s\n",
1195                                             fbuf);
1196                                         exit_cleanup(RERR_SYNTAX);
1197                                 }
1198                         }
1199                 }
1200
1201                 if (!*fn) {
1202                         len = 1;
1203                         fn = ".";
1204                 }
1205
1206                 if (dir && *dir) {
1207                         static char *lastdir;
1208                         static int lastdir_len;
1209
1210                         strlcpy(olddir, curr_dir, sizeof olddir);
1211
1212                         if (!push_dir(dir)) {
1213                                 io_error |= IOERR_GENERAL;
1214                                 rsyserr(FERROR, errno, "push_dir %s failed",
1215                                         full_fname(dir));
1216                                 continue;
1217                         }
1218
1219                         if (lastdir && strcmp(lastdir, dir) == 0) {
1220                                 flist_dir = lastdir;
1221                                 flist_dir_len = lastdir_len;
1222                         } else {
1223                                 flist_dir = lastdir = strdup(dir);
1224                                 flist_dir_len = lastdir_len = strlen(dir);
1225                         }
1226                 }
1227
1228                 if (fn != fbuf)
1229                         memmove(fbuf, fn, len + 1);
1230
1231                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1232                         /* Send the implied directories at the start of the
1233                          * source spec, so we get their permissions right. */
1234                         char *lp = lastpath, *slash = fbuf;
1235                         *p = '\0';
1236                         /* Skip any initial directories in our path that we
1237                          * have in common with lastpath. */
1238                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1239                                 if (*fn == '/')
1240                                         slash = fn;
1241                         }
1242                         *p = '/';
1243                         if (fn != p || (*lp && *lp != '/')) {
1244                                 int save_copy_links = copy_links;
1245                                 int save_xfer_dirs = xfer_dirs;
1246                                 copy_links |= copy_unsafe_links;
1247                                 xfer_dirs = 1;
1248                                 while ((slash = strchr(slash+1, '/')) != 0) {
1249                                         *slash = '\0';
1250                                         send_file_name(f, flist, fbuf, NULL, 0);
1251                                         *slash = '/';
1252                                 }
1253                                 copy_links = save_copy_links;
1254                                 xfer_dirs = save_xfer_dirs;
1255                                 *p = '\0';
1256                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1257                                 *p = '/';
1258                         }
1259                 }
1260
1261                 if (one_file_system)
1262                         filesystem_dev = st.st_dev;
1263
1264                 if (recurse || (xfer_dirs && is_dot_dir)) {
1265                         struct file_struct *file;
1266                         file = send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR);
1267                         if (file)
1268                                 send_if_directory(f, flist, file, fbuf, len);
1269                 } else
1270                         send_file_name(f, flist, fbuf, &st, 0);
1271
1272                 if (olddir[0]) {
1273                         flist_dir = NULL;
1274                         flist_dir_len = 0;
1275                         if (!pop_dir(olddir)) {
1276                                 rsyserr(FERROR, errno, "pop_dir %s failed",
1277                                         full_fname(olddir));
1278                                 exit_cleanup(RERR_FILESELECT);
1279                         }
1280                 }
1281         }
1282
1283         gettimeofday(&end_tv, NULL);
1284         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1285                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1286         if (stats.flist_buildtime == 0)
1287                 stats.flist_buildtime = 1;
1288         start_tv = end_tv;
1289
1290         send_file_entry(NULL, f);
1291
1292         if (show_filelist_p())
1293                 finish_filelist_progress(flist);
1294
1295         gettimeofday(&end_tv, NULL);
1296         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1297                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1298
1299         if (flist->hlink_pool) {
1300                 pool_destroy(flist->hlink_pool);
1301                 flist->hlink_pool = NULL;
1302         }
1303
1304         /* Sort the list without removing any duplicates.  This allows the
1305          * receiving side to ask for any name they like, which gives us the
1306          * flexibility to change the way we unduplicate names in the future
1307          * without causing a compatibility problem with older versions. */
1308         clean_flist(flist, 0, 0);
1309
1310         send_uid_list(f);
1311
1312         /* send the io_error flag */
1313         write_int(f, lp_ignore_errors(module_id) ? 0 : io_error);
1314
1315         io_end_buffering();
1316         stats.flist_size = stats.total_written - start_write;
1317         stats.num_files = flist->count;
1318
1319         if (verbose > 3)
1320                 output_flist(flist);
1321
1322         if (verbose > 2)
1323                 rprintf(FINFO, "send_file_list done\n");
1324
1325         return flist;
1326 }
1327
1328 struct file_list *recv_file_list(int f)
1329 {
1330         struct file_list *flist;
1331         unsigned short flags;
1332         int64 start_read;
1333
1334         rprintf(FLOG, "receiving file list\n");
1335         if (show_filelist_p())
1336                 start_filelist_progress("receiving file list");
1337
1338         start_read = stats.total_read;
1339
1340         flist = flist_new(WITH_HLINK, "recv_file_list");
1341
1342         flist->count = 0;
1343         flist->malloced = 1000;
1344         flist->files = new_array(struct file_struct *, flist->malloced);
1345         if (!flist->files)
1346                 goto oom;
1347
1348         while ((flags = read_byte(f)) != 0) {
1349                 struct file_struct *file;
1350
1351                 flist_expand(flist);
1352
1353                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1354                         flags |= read_byte(f) << 8;
1355                 file = receive_file_entry(flist, flags, f);
1356
1357                 if (S_ISREG(file->mode) || S_ISLNK(file->mode))
1358                         stats.total_size += file->length;
1359
1360                 flist->files[flist->count++] = file;
1361
1362                 maybe_emit_filelist_progress(flist->count);
1363
1364                 if (verbose > 2) {
1365                         rprintf(FINFO, "recv_file_name(%s)\n",
1366                                 f_name(file, NULL));
1367                 }
1368         }
1369         receive_file_entry(NULL, 0, 0); /* Signal that we're done. */
1370
1371         if (verbose > 2)
1372                 rprintf(FINFO, "received %d names\n", flist->count);
1373
1374         if (show_filelist_p())
1375                 finish_filelist_progress(flist);
1376
1377         clean_flist(flist, relative_paths, 1);
1378
1379         if (f >= 0) {
1380                 recv_uid_list(f, flist);
1381
1382                 /* Recv the io_error flag */
1383                 if (lp_ignore_errors(module_id) || ignore_errors)
1384                         read_int(f);
1385                 else
1386                         io_error |= read_int(f);
1387         }
1388
1389         if (verbose > 3)
1390                 output_flist(flist);
1391
1392         if (list_only) {
1393                 int i;
1394                 for (i = 0; i < flist->count; i++)
1395                         list_file_entry(flist->files[i]);
1396         }
1397
1398         if (verbose > 2)
1399                 rprintf(FINFO, "recv_file_list done\n");
1400
1401         stats.flist_size = stats.total_read - start_read;
1402         stats.num_files = flist->count;
1403
1404         return flist;
1405
1406   oom:
1407         out_of_memory("recv_file_list");
1408         return NULL;            /* not reached */
1409 }
1410
1411 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1412 {
1413         return f_name_cmp(*file1, *file2);
1414 }
1415
1416 /* Search for an identically-named item in the file list.  Note that the
1417  * items must agree in their directory-ness, or no match is returned. */
1418 int flist_find(struct file_list *flist, struct file_struct *f)
1419 {
1420         int low = flist->low, high = flist->high;
1421         int diff, mid, mid_up;
1422
1423         while (low <= high) {
1424                 mid = (low + high) / 2;
1425                 if (flist->files[mid]->basename)
1426                         mid_up = mid;
1427                 else {
1428                         /* Scan for the next non-empty entry using the cached
1429                          * distance values.  If the value isn't fully up-to-
1430                          * date, update it. */
1431                         mid_up = mid + flist->files[mid]->dir.depth;
1432                         if (!flist->files[mid_up]->basename) {
1433                                 do {
1434                                     mid_up += flist->files[mid_up]->dir.depth;
1435                                 } while (!flist->files[mid_up]->basename);
1436                                 flist->files[mid]->dir.depth = mid_up - mid;
1437                         }
1438                         if (mid_up > high) {
1439                                 /* If there's nothing left above us, set high to
1440                                  * a non-empty entry below us and continue. */
1441                                 high = mid - flist->files[mid]->length;
1442                                 if (!flist->files[high]->basename) {
1443                                         do {
1444                                             high -= flist->files[high]->length;
1445                                         } while (!flist->files[high]->basename);
1446                                         flist->files[mid]->length = mid - high;
1447                                 }
1448                                 continue;
1449                         }
1450                 }
1451                 diff = f_name_cmp(flist->files[mid_up], f);
1452                 if (diff == 0) {
1453                         if (protocol_version < 29
1454                             && S_ISDIR(flist->files[mid_up]->mode)
1455                             != S_ISDIR(f->mode))
1456                                 return -1;
1457                         return mid_up;
1458                 }
1459                 if (diff < 0)
1460                         low = mid_up + 1;
1461                 else
1462                         high = mid - 1;
1463         }
1464         return -1;
1465 }
1466
1467 /*
1468  * Free up any resources a file_struct has allocated
1469  * and clear the file.
1470  */
1471 void clear_file(struct file_struct *file, struct file_list *flist)
1472 {
1473         if (flist->hlink_pool && file->link_u.idev)
1474                 pool_free(flist->hlink_pool, 0, file->link_u.idev);
1475         memset(file, 0, file_struct_len);
1476         /* In an empty entry, dir.depth is an offset to the next non-empty
1477          * entry.  Likewise for length in the opposite direction.  We assume
1478          * that we're alone for now since flist_find() will adjust the counts
1479          * it runs into that aren't up-to-date. */
1480         file->length = file->dir.depth = 1;
1481 }
1482
1483 /*
1484  * allocate a new file list
1485  */
1486 struct file_list *flist_new(int with_hlink, char *msg)
1487 {
1488         struct file_list *flist;
1489
1490         flist = new(struct file_list);
1491         if (!flist)
1492                 out_of_memory(msg);
1493
1494         memset(flist, 0, sizeof (struct file_list));
1495
1496         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0,
1497             out_of_memory, POOL_INTERN)))
1498                 out_of_memory(msg);
1499
1500 #ifdef SUPPORT_HARD_LINKS
1501         if (with_hlink && preserve_hard_links) {
1502                 if (!(flist->hlink_pool = pool_create(HLINK_EXTENT,
1503                     sizeof (struct idev), out_of_memory, POOL_INTERN)))
1504                         out_of_memory(msg);
1505         }
1506 #endif
1507
1508         return flist;
1509 }
1510
1511 /*
1512  * free up all elements in a flist
1513  */
1514 void flist_free(struct file_list *flist)
1515 {
1516         pool_destroy(flist->file_pool);
1517         pool_destroy(flist->hlink_pool);
1518         free(flist->files);
1519         free(flist);
1520 }
1521
1522 /*
1523  * This routine ensures we don't have any duplicate names in our file list.
1524  * duplicate names can cause corruption because of the pipelining
1525  */
1526 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1527 {
1528         char fbuf[MAXPATHLEN];
1529         int i, prev_i = 0;
1530
1531         if (!flist)
1532                 return;
1533         if (flist->count == 0) {
1534                 flist->high = -1;
1535                 return;
1536         }
1537
1538         qsort(flist->files, flist->count,
1539             sizeof flist->files[0], (int (*)())file_compare);
1540
1541         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1542                 if (flist->files[i]->basename) {
1543                         prev_i = i;
1544                         break;
1545                 }
1546         }
1547         flist->low = prev_i;
1548         while (++i < flist->count) {
1549                 int j;
1550                 struct file_struct *file = flist->files[i];
1551
1552                 if (!file->basename)
1553                         continue;
1554                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1555                         j = prev_i;
1556                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1557                         int save_mode = file->mode;
1558                         /* Make sure that this directory doesn't duplicate a
1559                          * non-directory earlier in the list. */
1560                         flist->high = prev_i;
1561                         file->mode = S_IFREG;
1562                         j = flist_find(flist, file);
1563                         file->mode = save_mode;
1564                 } else
1565                         j = -1;
1566                 if (j >= 0) {
1567                         struct file_struct *fp = flist->files[j];
1568                         int keep, drop;
1569                         /* If one is a dir and the other is not, we want to
1570                          * keep the dir because it might have contents in the
1571                          * list. */
1572                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1573                                 if (S_ISDIR(file->mode))
1574                                         keep = i, drop = j;
1575                                 else
1576                                         keep = j, drop = i;
1577                         } else
1578                                 keep = j, drop = i;
1579                         if (verbose > 1 && !am_server) {
1580                                 rprintf(FINFO,
1581                                         "removing duplicate name %s from file list (%d)\n",
1582                                         f_name(file, fbuf), drop);
1583                         }
1584                         /* Make sure we don't lose track of a user-specified
1585                          * top directory. */
1586                         flist->files[keep]->flags |= flist->files[drop]->flags
1587                                                    & (FLAG_TOP_DIR|FLAG_DEL_HERE);
1588
1589                         clear_file(flist->files[drop], flist);
1590
1591                         if (keep == i) {
1592                                 if (flist->low == drop) {
1593                                         for (j = drop + 1;
1594                                              j < i && !flist->files[j]->basename;
1595                                              j++) {}
1596                                         flist->low = j;
1597                                 }
1598                                 prev_i = i;
1599                         }
1600                 } else
1601                         prev_i = i;
1602         }
1603         flist->high = no_dups ? prev_i : flist->count - 1;
1604
1605         if (strip_root) {
1606                 /* We need to strip off the leading slashes for relative
1607                  * paths, but this must be done _after_ the sorting phase. */
1608                 for (i = flist->low; i <= flist->high; i++) {
1609                         struct file_struct *file = flist->files[i];
1610
1611                         if (!file->dirname)
1612                                 continue;
1613                         while (*file->dirname == '/')
1614                                 file->dirname++;
1615                         if (!*file->dirname)
1616                                 file->dirname = NULL;
1617                 }
1618         }
1619
1620         if (prune_empty_dirs && no_dups) {
1621                 int j, prev_depth = 0;
1622
1623                 prev_i = 0; /* It's OK that this isn't really true. */
1624
1625                 for (i = flist->low; i <= flist->high; i++) {
1626                         struct file_struct *fp, *file = flist->files[i];
1627
1628                         /* This temporarily abuses the dir.depth value for a
1629                          * directory that is in a chain that might get pruned.
1630                          * We restore the old value if it gets a reprieve. */
1631                         if (S_ISDIR(file->mode) && file->dir.depth) {
1632                                 /* Dump empty dirs when coming back down. */
1633                                 for (j = prev_depth; j >= file->dir.depth; j--) {
1634                                         fp = flist->files[prev_i];
1635                                         if (fp->dir.depth >= 0)
1636                                                 break;
1637                                         prev_i = -fp->dir.depth-1;
1638                                         clear_file(fp, flist);
1639                                 }
1640                                 prev_depth = file->dir.depth;
1641                                 if (is_excluded(f_name(file, fbuf), 1,
1642                                                        ALL_FILTERS)) {
1643                                         /* Keep dirs through this dir. */
1644                                         for (j = prev_depth-1; ; j--) {
1645                                                 fp = flist->files[prev_i];
1646                                                 if (fp->dir.depth >= 0)
1647                                                         break;
1648                                                 prev_i = -fp->dir.depth-1;
1649                                                 fp->dir.depth = j;
1650                                         }
1651                                 } else
1652                                         file->dir.depth = -prev_i-1;
1653                                 prev_i = i;
1654                         } else {
1655                                 /* Keep dirs through this non-dir. */
1656                                 for (j = prev_depth; ; j--) {
1657                                         fp = flist->files[prev_i];
1658                                         if (fp->dir.depth >= 0)
1659                                                 break;
1660                                         prev_i = -fp->dir.depth-1;
1661                                         fp->dir.depth = j;
1662                                 }
1663                         }
1664                 }
1665                 /* Dump empty all remaining empty dirs. */
1666                 while (1) {
1667                         struct file_struct *fp = flist->files[prev_i];
1668                         if (fp->dir.depth >= 0)
1669                                 break;
1670                         prev_i = -fp->dir.depth-1;
1671                         clear_file(fp, flist);
1672                 }
1673
1674                 for (i = flist->low; i <= flist->high; i++) {
1675                         if (flist->files[i]->basename)
1676                                 break;
1677                 }
1678                 flist->low = i;
1679                 for (i = flist->high; i >= flist->low; i--) {
1680                         if (flist->files[i]->basename)
1681                                 break;
1682                 }
1683                 flist->high = i;
1684         }
1685 }
1686
1687 static void output_flist(struct file_list *flist)
1688 {
1689         char uidbuf[16], gidbuf[16], depthbuf[16];
1690         struct file_struct *file;
1691         const char *who = who_am_i();
1692         int i;
1693
1694         for (i = 0; i < flist->count; i++) {
1695                 file = flist->files[i];
1696                 if ((am_root || am_sender) && preserve_uid)
1697                         sprintf(uidbuf, " uid=%ld", (long)file->uid);
1698                 else
1699                         *uidbuf = '\0';
1700                 if (preserve_gid && file->gid != GID_NONE)
1701                         sprintf(gidbuf, " gid=%ld", (long)file->gid);
1702                 else
1703                         *gidbuf = '\0';
1704                 if (!am_sender)
1705                         sprintf(depthbuf, "%d", file->dir.depth);
1706                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
1707                         who, i, am_sender ? NS(file->dir.root) : depthbuf,
1708                         file->dirname ? file->dirname : "",
1709                         file->dirname ? "/" : "", NS(file->basename),
1710                         S_ISDIR(file->mode) ? "/" : "", (int)file->mode,
1711                         (double)file->length, uidbuf, gidbuf, file->flags);
1712         }
1713 }
1714
1715 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
1716 enum fnc_type { t_PATH, t_ITEM };
1717
1718 /* Compare the names of two file_struct entities, similar to how strcmp()
1719  * would do if it were operating on the joined strings.
1720  *
1721  * Some differences beginning with protocol_version 29: (1) directory names
1722  * are compared with an assumed trailing slash so that they compare in a
1723  * way that would cause them to sort immediately prior to any content they
1724  * may have; (2) a directory of any name compares after a non-directory of
1725  * any name at the same depth; (3) a directory with name "." compares prior
1726  * to anything else.  These changes mean that a directory and a non-dir
1727  * with the same name will not compare as equal (protocol_version >= 29).
1728  *
1729  * The dirname component can be an empty string, but the basename component
1730  * cannot (and never is in the current codebase).  The basename component
1731  * may be NULL (for a removed item), in which case it is considered to be
1732  * after any existing item. */
1733 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
1734 {
1735         int dif;
1736         const uchar *c1, *c2;
1737         enum fnc_state state1, state2;
1738         enum fnc_type type1, type2;
1739         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
1740
1741         if (!f1 || !f1->basename) {
1742                 if (!f2 || !f2->basename)
1743                         return 0;
1744                 return -1;
1745         }
1746         if (!f2 || !f2->basename)
1747                 return 1;
1748
1749         c1 = (uchar*)f1->dirname;
1750         c2 = (uchar*)f2->dirname;
1751         if (c1 == c2)
1752                 c1 = c2 = NULL;
1753         if (!c1) {
1754                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1755                 c1 = (uchar*)f1->basename;
1756                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1757                         type1 = t_ITEM;
1758                         state1 = s_TRAILING;
1759                         c1 = (uchar*)"";
1760                 } else
1761                         state1 = s_BASE;
1762         } else if (!*c1) {
1763                 type1 = t_path;
1764                 state1 = s_SLASH;
1765                 c1 = (uchar*)"/";
1766         } else {
1767                 type1 = t_path;
1768                 state1 = s_DIR;
1769         }
1770         if (!c2) {
1771                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1772                 c2 = (uchar*)f2->basename;
1773                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1774                         type2 = t_ITEM;
1775                         state2 = s_TRAILING;
1776                         c2 = (uchar*)"";
1777                 } else
1778                         state2 = s_BASE;
1779         } else if (!*c2) {
1780                 type2 = t_path;
1781                 state2 = s_SLASH;
1782                 c2 = (uchar*)"/";
1783         } else {
1784                 type2 = t_path;
1785                 state2 = s_DIR;
1786         }
1787
1788         if (type1 != type2)
1789                 return type1 == t_PATH ? 1 : -1;
1790
1791         while (1) {
1792                 if ((dif = (int)*c1++ - (int)*c2++) != 0)
1793                         break;
1794                 if (!*c1) {
1795                         switch (state1) {
1796                         case s_DIR:
1797                                 state1 = s_SLASH;
1798                                 c1 = (uchar*)"/";
1799                                 break;
1800                         case s_SLASH:
1801                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1802                                 c1 = (uchar*)f1->basename;
1803                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1804                                         type1 = t_ITEM;
1805                                         state1 = s_TRAILING;
1806                                         c1 = (uchar*)"";
1807                                 } else
1808                                         state1 = s_BASE;
1809                                 break;
1810                         case s_BASE:
1811                                 state1 = s_TRAILING;
1812                                 if (type1 == t_PATH) {
1813                                         c1 = (uchar*)"/";
1814                                         break;
1815                                 }
1816                                 /* FALL THROUGH */
1817                         case s_TRAILING:
1818                                 type1 = t_ITEM;
1819                                 break;
1820                         }
1821                         if (*c2 && type1 != type2)
1822                                 return type1 == t_PATH ? 1 : -1;
1823                 }
1824                 if (!*c2) {
1825                         switch (state2) {
1826                         case s_DIR:
1827                                 state2 = s_SLASH;
1828                                 c2 = (uchar*)"/";
1829                                 break;
1830                         case s_SLASH:
1831                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1832                                 c2 = (uchar*)f2->basename;
1833                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1834                                         type2 = t_ITEM;
1835                                         state2 = s_TRAILING;
1836                                         c2 = (uchar*)"";
1837                                 } else
1838                                         state2 = s_BASE;
1839                                 break;
1840                         case s_BASE:
1841                                 state2 = s_TRAILING;
1842                                 if (type2 == t_PATH) {
1843                                         c2 = (uchar*)"/";
1844                                         break;
1845                                 }
1846                                 /* FALL THROUGH */
1847                         case s_TRAILING:
1848                                 if (!*c1)
1849                                         return 0;
1850                                 type2 = t_ITEM;
1851                                 break;
1852                         }
1853                         if (type1 != type2)
1854                                 return type1 == t_PATH ? 1 : -1;
1855                 }
1856         }
1857
1858         return dif;
1859 }
1860
1861 /* Return a copy of the full filename of a flist entry, using the indicated
1862  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
1863  * done because we checked the size when creating the file_struct entry.
1864  */
1865 char *f_name(struct file_struct *f, char *fbuf)
1866 {
1867         if (!f || !f->basename)
1868                 return NULL;
1869
1870         if (!fbuf) {
1871                 static char names[5][MAXPATHLEN];
1872                 static unsigned int n;
1873
1874                 n = (n + 1) % (sizeof names / sizeof names[0]);
1875
1876                 fbuf = names[n];
1877         }
1878
1879         if (f->dirname) {
1880                 int len = strlen(f->dirname);
1881                 memcpy(fbuf, f->dirname, len);
1882                 fbuf[len] = '/';
1883                 strcpy(fbuf + len + 1, f->basename);
1884         } else
1885                 strcpy(fbuf, f->basename);
1886
1887         return fbuf;
1888 }
1889
1890 /* Do a non-recursive scan of the named directory, possibly ignoring all
1891  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
1892  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
1893  * buffer (the functions we call will append names onto the end, but the old
1894  * dir value will be restored on exit). */
1895 struct file_list *get_dirlist(char *dirname, int dlen,
1896                               int ignore_filter_rules)
1897 {
1898         struct file_list *dirlist;
1899         char dirbuf[MAXPATHLEN];
1900         int save_recurse = recurse;
1901         int save_xfer_dirs = xfer_dirs;
1902
1903         if (dlen < 0) {
1904                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
1905                 if (dlen >= MAXPATHLEN)
1906                         return NULL;
1907                 dirname = dirbuf;
1908         }
1909
1910         dirlist = flist_new(WITHOUT_HLINK, "get_dirlist");
1911
1912         recurse = 0;
1913         xfer_dirs = 1;
1914         send_directory(ignore_filter_rules ? -2 : -1, dirlist, dirname, dlen);
1915         xfer_dirs = save_xfer_dirs;
1916         recurse = save_recurse;
1917         if (do_progress)
1918                 flist_count_offset += dirlist->count;
1919
1920         clean_flist(dirlist, 0, 0);
1921
1922         if (verbose > 3)
1923                 output_flist(dirlist);
1924
1925         return dirlist;
1926 }