Some demon_log_* variables changed into logfile_* variables that are
[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(FINFO, "%s ... ", kind);
94         if (verbose > 1 || do_progress)
95                 rprintf(FINFO, "\n");
96         rflush(FINFO);
97 }
98
99 static void emit_filelist_progress(int count)
100 {
101         rprintf(FINFO, " %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(FINFO, "[%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                 bp += linkname_len;
659         }
660 #endif
661
662 #ifdef SUPPORT_HARD_LINKS
663         if (preserve_hard_links && protocol_version < 28 && S_ISREG(mode))
664                 flags |= XMIT_HAS_IDEV_DATA;
665         if (flags & XMIT_HAS_IDEV_DATA) {
666                 int64 inode;
667                 if (protocol_version < 26) {
668                         dev = read_int(f);
669                         inode = read_int(f);
670                 } else {
671                         if (!(flags & XMIT_SAME_DEV))
672                                 dev = read_longint(f);
673                         inode = read_longint(f);
674                 }
675                 if (flist->hlink_pool) {
676                         file->link_u.idev = pool_talloc(flist->hlink_pool,
677                             struct idev, 1, "inode_table");
678                         file->F_INODE = inode;
679                         file->F_DEV = dev;
680                 }
681         }
682 #endif
683
684         if (always_checksum && (sum_len || protocol_version < 28)) {
685                 char *sum;
686                 if (sum_len) {
687                         file->u.sum = sum = bp;
688                         /*bp += sum_len;*/
689                 } else {
690                         /* Prior to 28, we get a useless set of nulls. */
691                         sum = empty_sum;
692                 }
693                 read_buf(f, sum, checksum_len);
694         }
695
696         return file;
697 }
698
699 /**
700  * Create a file_struct for a named file by reading its stat()
701  * information and performing extensive checks against global
702  * options.
703  *
704  * @return the new file, or NULL if there was an error or this file
705  * should be excluded.
706  *
707  * @todo There is a small optimization opportunity here to avoid
708  * stat()ing the file in some circumstances, which has a certain cost.
709  * We are called immediately after doing readdir(), and so we may
710  * already know the d_type of the file.  We could for example avoid
711  * statting directories if we're not recursing, but this is not a very
712  * important case.  Some systems may not have d_type.
713  **/
714 struct file_struct *make_file(char *fname, struct file_list *flist,
715                               STRUCT_STAT *stp, unsigned short flags,
716                               int filter_level)
717 {
718         static char *lastdir;
719         static int lastdir_len = -1;
720         struct file_struct *file;
721         STRUCT_STAT st;
722         char sum[SUM_LENGTH];
723         char thisname[MAXPATHLEN];
724         char linkname[MAXPATHLEN];
725         int alloc_len, basename_len, dirname_len, linkname_len, sum_len;
726         char *basename, *dirname, *bp;
727
728         if (!flist || !flist->count)    /* Ignore lastdir when invalid. */
729                 lastdir_len = -1;
730
731         if (strlcpy(thisname, fname, sizeof thisname)
732             >= sizeof thisname - flist_dir_len) {
733                 rprintf(FINFO, "skipping overly long name: %s\n", fname);
734                 return NULL;
735         }
736         clean_fname(thisname, 0);
737         if (sanitize_paths)
738                 sanitize_path(thisname, thisname, "", 0, NULL);
739
740         memset(sum, 0, SUM_LENGTH);
741
742         if (stp && S_ISDIR(stp->st_mode))
743                 st = *stp; /* Needed for "symlink/." with --relative. */
744         else if (readlink_stat(thisname, &st, linkname) != 0) {
745                 int save_errno = errno;
746                 /* See if file is excluded before reporting an error. */
747                 if (filter_level != NO_FILTERS
748                     && is_excluded(thisname, 0, filter_level))
749                         return NULL;
750                 if (save_errno == ENOENT) {
751 #ifdef SUPPORT_LINKS
752                         /* Avoid "vanished" error if symlink points nowhere. */
753                         if (copy_links && do_lstat(thisname, &st) == 0
754                             && S_ISLNK(st.st_mode)) {
755                                 io_error |= IOERR_GENERAL;
756                                 rprintf(FERROR, "symlink has no referent: %s\n",
757                                         full_fname(thisname));
758                         } else
759 #endif
760                         {
761                                 enum logcode c = am_daemon && protocol_version < 28
762                                     ? FERROR : FINFO;
763                                 io_error |= IOERR_VANISHED;
764                                 rprintf(c, "file has vanished: %s\n",
765                                         full_fname(thisname));
766                         }
767                 } else {
768                         io_error |= IOERR_GENERAL;
769                         rsyserr(FERROR, save_errno, "readlink %s failed",
770                                 full_fname(thisname));
771                 }
772                 return NULL;
773         }
774
775         /* backup.c calls us with filter_level set to NO_FILTERS. */
776         if (filter_level == NO_FILTERS)
777                 goto skip_filters;
778
779         if (S_ISDIR(st.st_mode) && !xfer_dirs) {
780                 rprintf(FINFO, "skipping directory %s\n", thisname);
781                 return NULL;
782         }
783
784         /* We only care about directories because we need to avoid recursing
785          * into a mount-point directory, not to avoid copying a symlinked
786          * file if -L (or similar) was specified. */
787         if (one_file_system && st.st_dev != filesystem_dev
788          && S_ISDIR(st.st_mode)) {
789                 if (one_file_system > 1) {
790                         if (verbose > 2) {
791                                 rprintf(FINFO, "skipping mount-point dir %s\n",
792                                         thisname);
793                         }
794                         return NULL;
795                 }
796                 flags |= FLAG_MOUNT_POINT;
797         }
798
799         if (is_excluded(thisname, S_ISDIR(st.st_mode) != 0, filter_level))
800                 return NULL;
801
802         if (lp_ignore_nonreadable(module_id)) {
803 #ifdef SUPPORT_LINKS
804                 if (!S_ISLNK(st.st_mode))
805 #endif
806                         if (access(thisname, R_OK) != 0)
807                                 return NULL;
808         }
809
810   skip_filters:
811
812         if (verbose > 2) {
813                 rprintf(FINFO, "[%s] make_file(%s,*,%d)\n",
814                         who_am_i(), thisname, filter_level);
815         }
816
817         if ((basename = strrchr(thisname, '/')) != NULL) {
818                 dirname_len = ++basename - thisname; /* counts future '\0' */
819                 if (lastdir_len == dirname_len - 1
820                     && strncmp(thisname, lastdir, lastdir_len) == 0) {
821                         dirname = lastdir;
822                         dirname_len = 0; /* indicates no copy is needed */
823                 } else
824                         dirname = thisname;
825         } else {
826                 basename = thisname;
827                 dirname = NULL;
828                 dirname_len = 0;
829         }
830         basename_len = strlen(basename) + 1; /* count the '\0' */
831
832 #ifdef SUPPORT_LINKS
833         linkname_len = S_ISLNK(st.st_mode) ? strlen(linkname) + 1 : 0;
834 #else
835         linkname_len = 0;
836 #endif
837
838         sum_len = always_checksum && am_sender && S_ISREG(st.st_mode)
839                 ? MD4_SUM_LENGTH : 0;
840
841         alloc_len = file_struct_len + dirname_len + basename_len
842                   + linkname_len + sum_len;
843         if (flist)
844                 bp = pool_alloc(flist->file_pool, alloc_len, "make_file");
845         else {
846                 if (!(bp = new_array(char, alloc_len)))
847                         out_of_memory("make_file");
848         }
849
850         file = (struct file_struct *)bp;
851         memset(bp, 0, file_struct_len);
852         bp += file_struct_len;
853
854         file->flags = flags;
855         file->modtime = st.st_mtime;
856         file->length = st.st_size;
857         file->mode = st.st_mode;
858         file->uid = st.st_uid;
859         file->gid = st.st_gid;
860
861 #ifdef SUPPORT_HARD_LINKS
862         if (flist && flist->hlink_pool) {
863                 if (protocol_version < 28) {
864                         if (S_ISREG(st.st_mode))
865                                 file->link_u.idev = pool_talloc(
866                                     flist->hlink_pool, struct idev, 1,
867                                     "inode_table");
868                 } else {
869                         if (!S_ISDIR(st.st_mode) && st.st_nlink > 1)
870                                 file->link_u.idev = pool_talloc(
871                                     flist->hlink_pool, struct idev, 1,
872                                     "inode_table");
873                 }
874         }
875         if (file->link_u.idev) {
876                 file->F_DEV = st.st_dev;
877                 file->F_INODE = st.st_ino;
878         }
879 #endif
880
881         if (dirname_len) {
882                 file->dirname = lastdir = bp;
883                 lastdir_len = dirname_len - 1;
884                 memcpy(bp, dirname, dirname_len - 1);
885                 bp += dirname_len;
886                 bp[-1] = '\0';
887         } else if (dirname)
888                 file->dirname = dirname;
889
890         file->basename = bp;
891         memcpy(bp, basename, basename_len);
892         bp += basename_len;
893
894 #ifdef HAVE_STRUCT_STAT_ST_RDEV
895         if ((preserve_devices && IS_DEVICE(st.st_mode))
896          || (preserve_specials && IS_SPECIAL(st.st_mode)))
897                 file->u.rdev = st.st_rdev;
898 #endif
899
900 #ifdef SUPPORT_LINKS
901         if (linkname_len) {
902                 file->u.link = bp;
903                 memcpy(bp, linkname, linkname_len);
904                 bp += linkname_len;
905         }
906 #endif
907
908         if (sum_len) {
909                 file->u.sum = bp;
910                 file_checksum(thisname, bp, st.st_size);
911                 /*bp += sum_len;*/
912         }
913
914         file->dir.root = flist_dir;
915
916         /* This code is only used by the receiver when it is building
917          * a list of files for a delete pass. */
918         if (keep_dirlinks && linkname_len && flist) {
919                 STRUCT_STAT st2;
920                 int save_mode = file->mode;
921                 file->mode = S_IFDIR; /* Find a directory with our name. */
922                 if (flist_find(the_file_list, file) >= 0
923                     && safe_stat(thisname, &st2) == 0 && S_ISDIR(st2.st_mode)) {
924                         file->modtime = st2.st_mtime;
925                         file->length = st2.st_size;
926                         file->mode = st2.st_mode;
927                         file->uid = st2.st_uid;
928                         file->gid = st2.st_gid;
929                         file->u.link = NULL;
930                 } else
931                         file->mode = save_mode;
932         }
933
934         if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))
935                 stats.total_size += st.st_size;
936
937         return file;
938 }
939
940 static struct file_struct *send_file_name(int f, struct file_list *flist,
941                                           char *fname, STRUCT_STAT *stp,
942                                           unsigned short flags)
943 {
944         struct file_struct *file;
945
946         file = make_file(fname, flist, stp, flags,
947                          f == -2 ? SERVER_FILTERS : ALL_FILTERS);
948         if (!file)
949                 return NULL;
950
951         if (chmod_modes && !S_ISLNK(file->mode))
952                 file->mode = tweak_mode(file->mode, chmod_modes);
953
954         maybe_emit_filelist_progress(flist->count + flist_count_offset);
955
956         flist_expand(flist);
957
958         if (file->basename[0]) {
959                 flist->files[flist->count++] = file;
960                 send_file_entry(file, f);
961         }
962         return file;
963 }
964
965 static void send_if_directory(int f, struct file_list *flist,
966                               struct file_struct *file,
967                               char *fbuf, unsigned int ol)
968 {
969         char is_dot_dir = fbuf[ol-1] == '.' && (ol == 1 || fbuf[ol-2] == '/');
970
971         if (S_ISDIR(file->mode)
972             && !(file->flags & FLAG_MOUNT_POINT) && f_name(file, fbuf)) {
973                 void *save_filters;
974                 unsigned int len = strlen(fbuf);
975                 if (len > 1 && fbuf[len-1] == '/')
976                         fbuf[--len] = '\0';
977                 if (len >= MAXPATHLEN - 1) {
978                         io_error |= IOERR_GENERAL;
979                         rprintf(FERROR, "skipping long-named directory: %s\n",
980                                 full_fname(fbuf));
981                         return;
982                 }
983                 save_filters = push_local_filters(fbuf, len);
984                 send_directory(f, flist, fbuf, len);
985                 pop_local_filters(save_filters);
986                 fbuf[ol] = '\0';
987                 if (is_dot_dir)
988                         fbuf[ol-1] = '.';
989         }
990 }
991
992 /* This function is normally called by the sender, but the receiving side also
993  * calls it from get_dirlist() with f set to -1 so that we just construct the
994  * file list in memory without sending it over the wire.  Also, get_dirlist()
995  * might call this with f set to -2, which also indicates that local filter
996  * rules should be ignored. */
997 static void send_directory(int f, struct file_list *flist,
998                            char *fbuf, int len)
999 {
1000         struct dirent *di;
1001         unsigned remainder;
1002         char *p;
1003         DIR *d;
1004         int start = flist->count;
1005
1006         if (!(d = opendir(fbuf))) {
1007                 io_error |= IOERR_GENERAL;
1008                 rsyserr(FERROR, errno, "opendir %s failed", full_fname(fbuf));
1009                 return;
1010         }
1011
1012         p = fbuf + len;
1013         if (len != 1 || *fbuf != '/')
1014                 *p++ = '/';
1015         *p = '\0';
1016         remainder = MAXPATHLEN - (p - fbuf);
1017
1018         for (errno = 0, di = readdir(d); di; errno = 0, di = readdir(d)) {
1019                 char *dname = d_name(di);
1020                 if (dname[0] == '.' && (dname[1] == '\0'
1021                     || (dname[1] == '.' && dname[2] == '\0')))
1022                         continue;
1023                 if (strlcpy(p, dname, remainder) >= remainder) {
1024                         io_error |= IOERR_GENERAL;
1025                         rprintf(FINFO,
1026                                 "cannot send long-named file %s\n",
1027                                 full_fname(fbuf));
1028                         continue;
1029                 }
1030
1031                 send_file_name(f, flist, fbuf, NULL, 0);
1032         }
1033
1034         fbuf[len] = '\0';
1035
1036         if (errno) {
1037                 io_error |= IOERR_GENERAL;
1038                 rsyserr(FERROR, errno, "readdir(%s)", full_fname(fbuf));
1039         }
1040
1041         closedir(d);
1042
1043         if (recurse) {
1044                 int i, end = flist->count - 1;
1045                 for (i = start; i <= end; i++)
1046                         send_if_directory(f, flist, flist->files[i], fbuf, len);
1047         }
1048 }
1049
1050 struct file_list *send_file_list(int f, int argc, char *argv[])
1051 {
1052         int len;
1053         STRUCT_STAT st;
1054         char *p, *dir, olddir[sizeof curr_dir];
1055         char lastpath[MAXPATHLEN] = "";
1056         struct file_list *flist;
1057         struct timeval start_tv, end_tv;
1058         int64 start_write;
1059         int use_ff_fd = 0;
1060
1061         if (show_filelist_p())
1062                 start_filelist_progress("building file list");
1063
1064         start_write = stats.total_written;
1065         gettimeofday(&start_tv, NULL);
1066
1067         flist = flist_new(WITH_HLINK, "send_file_list");
1068
1069         io_start_buffering_out();
1070         if (filesfrom_fd >= 0) {
1071                 if (sanitize_paths)
1072                         die_on_unsafe_path(argv[0], 0);
1073                 if (argv[0] && !push_dir(argv[0])) {
1074                         rsyserr(FERROR, errno, "push_dir %s failed",
1075                                 full_fname(argv[0]));
1076                         exit_cleanup(RERR_FILESELECT);
1077                 }
1078                 use_ff_fd = 1;
1079         }
1080
1081         while (1) {
1082                 char fbuf[MAXPATHLEN];
1083                 char *fn;
1084                 int is_dot_dir;
1085
1086                 if (use_ff_fd) {
1087                         if (read_filesfrom_line(filesfrom_fd, fbuf) == 0)
1088                                 break;
1089                         sanitize_path(fbuf, fbuf, "", 0, NULL);
1090                 } else {
1091                         if (argc-- == 0)
1092                                 break;
1093                         strlcpy(fbuf, *argv++, MAXPATHLEN);
1094                         if (sanitize_paths)
1095                                 sanitize_path(fbuf, fbuf, "", 0, NULL);
1096                 }
1097
1098                 len = strlen(fbuf);
1099                 if (relative_paths) {
1100                         /* We clean up fbuf below. */
1101                         is_dot_dir = 0;
1102                 } else if (!len || fbuf[len - 1] == '/') {
1103                         if (len == 2 && fbuf[0] == '.') {
1104                                 /* Turn "./" into just "." rather than "./." */
1105                                 fbuf[1] = '\0';
1106                         } else {
1107                                 if (len + 1 >= MAXPATHLEN)
1108                                         overflow_exit("send_file_list");
1109                                 fbuf[len++] = '.';
1110                                 fbuf[len] = '\0';
1111                         }
1112                         is_dot_dir = 1;
1113                 } else if (len > 1 && fbuf[len-1] == '.' && fbuf[len-2] == '.'
1114                     && (len == 2 || fbuf[len-3] == '/')) {
1115                         if (len + 2 >= MAXPATHLEN)
1116                                 overflow_exit("send_file_list");
1117                         fbuf[len++] = '/';
1118                         fbuf[len++] = '.';
1119                         fbuf[len] = '\0';
1120                         is_dot_dir = 1;
1121                 } else {
1122                         is_dot_dir = fbuf[len-1] == '.'
1123                                    && (len == 1 || fbuf[len-2] == '/');
1124                 }
1125
1126                 if (sanitize_paths)
1127                         die_on_unsafe_path(fbuf, 1);
1128                 if (link_stat(fbuf, &st, copy_dirlinks) != 0) {
1129                         io_error |= IOERR_GENERAL;
1130                         rsyserr(FERROR, errno, "link_stat %s failed",
1131                                 full_fname(fbuf));
1132                         continue;
1133                 }
1134
1135                 if (S_ISDIR(st.st_mode) && !xfer_dirs) {
1136                         rprintf(FINFO, "skipping directory %s\n", fbuf);
1137                         continue;
1138                 }
1139
1140                 dir = NULL;
1141                 olddir[0] = '\0';
1142
1143                 if (!relative_paths) {
1144                         p = strrchr(fbuf, '/');
1145                         if (p) {
1146                                 *p = '\0';
1147                                 if (p == fbuf)
1148                                         dir = "/";
1149                                 else
1150                                         dir = fbuf;
1151                                 len -= p - fbuf + 1;
1152                                 fn = p + 1;
1153                         } else
1154                                 fn = fbuf;
1155                 } else {
1156                         if ((p = strstr(fbuf, "/./")) != NULL) {
1157                                 *p = '\0';
1158                                 if (p == fbuf)
1159                                         dir = "/";
1160                                 else
1161                                         dir = fbuf;
1162                                 len -= p - fbuf + 3;
1163                                 fn = p + 3;
1164                         } else
1165                                 fn = fbuf;
1166                         /* Get rid of trailing "/" and "/.". */
1167                         while (len) {
1168                                 if (fn[len - 1] == '/') {
1169                                         is_dot_dir = 1;
1170                                         if (!--len && !dir) {
1171                                                 len++;
1172                                                 break;
1173                                         }
1174                                 }
1175                                 else if (len >= 2 && fn[len - 1] == '.'
1176                                                   && fn[len - 2] == '/') {
1177                                         is_dot_dir = 1;
1178                                         if (!(len -= 2) && !dir) {
1179                                                 len++;
1180                                                 break;
1181                                         }
1182                                 } else
1183                                         break;
1184                         }
1185                         fn[len] = '\0';
1186                         /* Reject a ".." dir in the active part of the path. */
1187                         for (p = fn; (p = strstr(p, "..")) != NULL; p += 2) {
1188                                 if ((p[2] == '/' || p[2] == '\0')
1189                                  && (p == fn || p[-1] == '/')) {
1190                                         rprintf(FERROR,
1191                                             "found \"..\" dir in relative path: %s\n",
1192                                             fbuf);
1193                                         exit_cleanup(RERR_SYNTAX);
1194                                 }
1195                         }
1196                 }
1197
1198                 if (!*fn) {
1199                         len = 1;
1200                         fn = ".";
1201                 }
1202
1203                 if (dir && *dir) {
1204                         static char *lastdir;
1205                         static int lastdir_len;
1206
1207                         strlcpy(olddir, curr_dir, sizeof olddir);
1208
1209                         if (!push_dir(dir)) {
1210                                 io_error |= IOERR_GENERAL;
1211                                 rsyserr(FERROR, errno, "push_dir %s failed",
1212                                         full_fname(dir));
1213                                 continue;
1214                         }
1215
1216                         if (lastdir && strcmp(lastdir, dir) == 0) {
1217                                 flist_dir = lastdir;
1218                                 flist_dir_len = lastdir_len;
1219                         } else {
1220                                 flist_dir = lastdir = strdup(dir);
1221                                 flist_dir_len = lastdir_len = strlen(dir);
1222                         }
1223                 }
1224
1225                 if (fn != fbuf)
1226                         memmove(fbuf, fn, len + 1);
1227
1228                 if (implied_dirs && (p=strrchr(fbuf,'/')) && p != fbuf) {
1229                         /* Send the implied directories at the start of the
1230                          * source spec, so we get their permissions right. */
1231                         char *lp = lastpath, *slash = fbuf;
1232                         *p = '\0';
1233                         /* Skip any initial directories in our path that we
1234                          * have in common with lastpath. */
1235                         for (fn = fbuf; *fn && *lp == *fn; lp++, fn++) {
1236                                 if (*fn == '/')
1237                                         slash = fn;
1238                         }
1239                         *p = '/';
1240                         if (fn != p || (*lp && *lp != '/')) {
1241                                 int save_copy_links = copy_links;
1242                                 int save_xfer_dirs = xfer_dirs;
1243                                 copy_links |= copy_unsafe_links;
1244                                 xfer_dirs = 1;
1245                                 while ((slash = strchr(slash+1, '/')) != 0) {
1246                                         *slash = '\0';
1247                                         send_file_name(f, flist, fbuf, NULL, 0);
1248                                         *slash = '/';
1249                                 }
1250                                 copy_links = save_copy_links;
1251                                 xfer_dirs = save_xfer_dirs;
1252                                 *p = '\0';
1253                                 strlcpy(lastpath, fbuf, sizeof lastpath);
1254                                 *p = '/';
1255                         }
1256                 }
1257
1258                 if (one_file_system)
1259                         filesystem_dev = st.st_dev;
1260
1261                 if (recurse || (xfer_dirs && is_dot_dir)) {
1262                         struct file_struct *file;
1263                         file = send_file_name(f, flist, fbuf, &st, FLAG_TOP_DIR);
1264                         if (file)
1265                                 send_if_directory(f, flist, file, fbuf, len);
1266                 } else
1267                         send_file_name(f, flist, fbuf, &st, 0);
1268
1269                 if (olddir[0]) {
1270                         flist_dir = NULL;
1271                         flist_dir_len = 0;
1272                         if (!pop_dir(olddir)) {
1273                                 rsyserr(FERROR, errno, "pop_dir %s failed",
1274                                         full_fname(olddir));
1275                                 exit_cleanup(RERR_FILESELECT);
1276                         }
1277                 }
1278         }
1279
1280         gettimeofday(&end_tv, NULL);
1281         stats.flist_buildtime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1282                               + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1283         if (stats.flist_buildtime == 0)
1284                 stats.flist_buildtime = 1;
1285         start_tv = end_tv;
1286
1287         send_file_entry(NULL, f);
1288
1289         if (show_filelist_p())
1290                 finish_filelist_progress(flist);
1291
1292         gettimeofday(&end_tv, NULL);
1293         stats.flist_xfertime = (int64)(end_tv.tv_sec - start_tv.tv_sec) * 1000
1294                              + (end_tv.tv_usec - start_tv.tv_usec) / 1000;
1295
1296         if (flist->hlink_pool) {
1297                 pool_destroy(flist->hlink_pool);
1298                 flist->hlink_pool = NULL;
1299         }
1300
1301         /* Sort the list without removing any duplicates.  This allows the
1302          * receiving side to ask for any name they like, which gives us the
1303          * flexibility to change the way we unduplicate names in the future
1304          * without causing a compatibility problem with older versions. */
1305         clean_flist(flist, 0, 0);
1306
1307         send_uid_list(f);
1308
1309         /* send the io_error flag */
1310         write_int(f, lp_ignore_errors(module_id) ? 0 : io_error);
1311
1312         io_end_buffering();
1313         stats.flist_size = stats.total_written - start_write;
1314         stats.num_files = flist->count;
1315
1316         if (verbose > 3)
1317                 output_flist(flist);
1318
1319         if (verbose > 2)
1320                 rprintf(FINFO, "send_file_list done\n");
1321
1322         return flist;
1323 }
1324
1325 struct file_list *recv_file_list(int f)
1326 {
1327         struct file_list *flist;
1328         unsigned short flags;
1329         int64 start_read;
1330
1331         if (show_filelist_p())
1332                 start_filelist_progress("receiving file list");
1333
1334         start_read = stats.total_read;
1335
1336         flist = flist_new(WITH_HLINK, "recv_file_list");
1337
1338         flist->count = 0;
1339         flist->malloced = 1000;
1340         flist->files = new_array(struct file_struct *, flist->malloced);
1341         if (!flist->files)
1342                 goto oom;
1343
1344         while ((flags = read_byte(f)) != 0) {
1345                 struct file_struct *file;
1346
1347                 flist_expand(flist);
1348
1349                 if (protocol_version >= 28 && (flags & XMIT_EXTENDED_FLAGS))
1350                         flags |= read_byte(f) << 8;
1351                 file = receive_file_entry(flist, flags, f);
1352
1353                 if (S_ISREG(file->mode) || S_ISLNK(file->mode))
1354                         stats.total_size += file->length;
1355
1356                 flist->files[flist->count++] = file;
1357
1358                 maybe_emit_filelist_progress(flist->count);
1359
1360                 if (verbose > 2) {
1361                         rprintf(FINFO, "recv_file_name(%s)\n",
1362                                 f_name(file, NULL));
1363                 }
1364         }
1365         receive_file_entry(NULL, 0, 0); /* Signal that we're done. */
1366
1367         if (verbose > 2)
1368                 rprintf(FINFO, "received %d names\n", flist->count);
1369
1370         if (show_filelist_p())
1371                 finish_filelist_progress(flist);
1372
1373         clean_flist(flist, relative_paths, 1);
1374
1375         if (f >= 0) {
1376                 recv_uid_list(f, flist);
1377
1378                 /* Recv the io_error flag */
1379                 if (lp_ignore_errors(module_id) || ignore_errors)
1380                         read_int(f);
1381                 else
1382                         io_error |= read_int(f);
1383         }
1384
1385         if (verbose > 3)
1386                 output_flist(flist);
1387
1388         if (list_only) {
1389                 int i;
1390                 for (i = 0; i < flist->count; i++)
1391                         list_file_entry(flist->files[i]);
1392         }
1393
1394         if (verbose > 2)
1395                 rprintf(FINFO, "recv_file_list done\n");
1396
1397         stats.flist_size = stats.total_read - start_read;
1398         stats.num_files = flist->count;
1399
1400         return flist;
1401
1402   oom:
1403         out_of_memory("recv_file_list");
1404         return NULL;            /* not reached */
1405 }
1406
1407 static int file_compare(struct file_struct **file1, struct file_struct **file2)
1408 {
1409         return f_name_cmp(*file1, *file2);
1410 }
1411
1412 /* Search for an identically-named item in the file list.  Note that the
1413  * items must agree in their directory-ness, or no match is returned. */
1414 int flist_find(struct file_list *flist, struct file_struct *f)
1415 {
1416         int low = flist->low, high = flist->high;
1417         int diff, mid, mid_up;
1418
1419         while (low <= high) {
1420                 mid = (low + high) / 2;
1421                 if (flist->files[mid]->basename)
1422                         mid_up = mid;
1423                 else {
1424                         /* Scan for the next non-empty entry using the cached
1425                          * distance values.  If the value isn't fully up-to-
1426                          * date, update it. */
1427                         mid_up = mid + flist->files[mid]->dir.depth;
1428                         if (!flist->files[mid_up]->basename) {
1429                                 do {
1430                                     mid_up += flist->files[mid_up]->dir.depth;
1431                                 } while (!flist->files[mid_up]->basename);
1432                                 flist->files[mid]->dir.depth = mid_up - mid;
1433                         }
1434                         if (mid_up > high) {
1435                                 /* If there's nothing left above us, set high to
1436                                  * a non-empty entry below us and continue. */
1437                                 high = mid - flist->files[mid]->length;
1438                                 if (!flist->files[high]->basename) {
1439                                         do {
1440                                             high -= flist->files[high]->length;
1441                                         } while (!flist->files[high]->basename);
1442                                         flist->files[mid]->length = mid - high;
1443                                 }
1444                                 continue;
1445                         }
1446                 }
1447                 diff = f_name_cmp(flist->files[mid_up], f);
1448                 if (diff == 0) {
1449                         if (protocol_version < 29
1450                             && S_ISDIR(flist->files[mid_up]->mode)
1451                             != S_ISDIR(f->mode))
1452                                 return -1;
1453                         return mid_up;
1454                 }
1455                 if (diff < 0)
1456                         low = mid_up + 1;
1457                 else
1458                         high = mid - 1;
1459         }
1460         return -1;
1461 }
1462
1463 /*
1464  * Free up any resources a file_struct has allocated
1465  * and clear the file.
1466  */
1467 void clear_file(struct file_struct *file, struct file_list *flist)
1468 {
1469         if (flist->hlink_pool && file->link_u.idev)
1470                 pool_free(flist->hlink_pool, 0, file->link_u.idev);
1471         memset(file, 0, file_struct_len);
1472         /* In an empty entry, dir.depth is an offset to the next non-empty
1473          * entry.  Likewise for length in the opposite direction.  We assume
1474          * that we're alone for now since flist_find() will adjust the counts
1475          * it runs into that aren't up-to-date. */
1476         file->length = file->dir.depth = 1;
1477 }
1478
1479 /*
1480  * allocate a new file list
1481  */
1482 struct file_list *flist_new(int with_hlink, char *msg)
1483 {
1484         struct file_list *flist;
1485
1486         flist = new(struct file_list);
1487         if (!flist)
1488                 out_of_memory(msg);
1489
1490         memset(flist, 0, sizeof (struct file_list));
1491
1492         if (!(flist->file_pool = pool_create(FILE_EXTENT, 0,
1493             out_of_memory, POOL_INTERN)))
1494                 out_of_memory(msg);
1495
1496 #ifdef SUPPORT_HARD_LINKS
1497         if (with_hlink && preserve_hard_links) {
1498                 if (!(flist->hlink_pool = pool_create(HLINK_EXTENT,
1499                     sizeof (struct idev), out_of_memory, POOL_INTERN)))
1500                         out_of_memory(msg);
1501         }
1502 #endif
1503
1504         return flist;
1505 }
1506
1507 /*
1508  * free up all elements in a flist
1509  */
1510 void flist_free(struct file_list *flist)
1511 {
1512         pool_destroy(flist->file_pool);
1513         pool_destroy(flist->hlink_pool);
1514         free(flist->files);
1515         free(flist);
1516 }
1517
1518 /*
1519  * This routine ensures we don't have any duplicate names in our file list.
1520  * duplicate names can cause corruption because of the pipelining
1521  */
1522 static void clean_flist(struct file_list *flist, int strip_root, int no_dups)
1523 {
1524         char fbuf[MAXPATHLEN];
1525         int i, prev_i = 0;
1526
1527         if (!flist)
1528                 return;
1529         if (flist->count == 0) {
1530                 flist->high = -1;
1531                 return;
1532         }
1533
1534         qsort(flist->files, flist->count,
1535             sizeof flist->files[0], (int (*)())file_compare);
1536
1537         for (i = no_dups? 0 : flist->count; i < flist->count; i++) {
1538                 if (flist->files[i]->basename) {
1539                         prev_i = i;
1540                         break;
1541                 }
1542         }
1543         flist->low = prev_i;
1544         while (++i < flist->count) {
1545                 int j;
1546                 struct file_struct *file = flist->files[i];
1547
1548                 if (!file->basename)
1549                         continue;
1550                 if (f_name_cmp(file, flist->files[prev_i]) == 0)
1551                         j = prev_i;
1552                 else if (protocol_version >= 29 && S_ISDIR(file->mode)) {
1553                         int save_mode = file->mode;
1554                         /* Make sure that this directory doesn't duplicate a
1555                          * non-directory earlier in the list. */
1556                         flist->high = prev_i;
1557                         file->mode = S_IFREG;
1558                         j = flist_find(flist, file);
1559                         file->mode = save_mode;
1560                 } else
1561                         j = -1;
1562                 if (j >= 0) {
1563                         struct file_struct *fp = flist->files[j];
1564                         int keep, drop;
1565                         /* If one is a dir and the other is not, we want to
1566                          * keep the dir because it might have contents in the
1567                          * list. */
1568                         if (S_ISDIR(file->mode) != S_ISDIR(fp->mode)) {
1569                                 if (S_ISDIR(file->mode))
1570                                         keep = i, drop = j;
1571                                 else
1572                                         keep = j, drop = i;
1573                         } else
1574                                 keep = j, drop = i;
1575                         if (verbose > 1 && !am_server) {
1576                                 rprintf(FINFO,
1577                                         "removing duplicate name %s from file list (%d)\n",
1578                                         f_name(file, fbuf), drop);
1579                         }
1580                         /* Make sure we don't lose track of a user-specified
1581                          * top directory. */
1582                         flist->files[keep]->flags |= flist->files[drop]->flags
1583                                                    & (FLAG_TOP_DIR|FLAG_DEL_HERE);
1584
1585                         clear_file(flist->files[drop], flist);
1586
1587                         if (keep == i) {
1588                                 if (flist->low == drop) {
1589                                         for (j = drop + 1;
1590                                              j < i && !flist->files[j]->basename;
1591                                              j++) {}
1592                                         flist->low = j;
1593                                 }
1594                                 prev_i = i;
1595                         }
1596                 } else
1597                         prev_i = i;
1598         }
1599         flist->high = no_dups ? prev_i : flist->count - 1;
1600
1601         if (strip_root) {
1602                 /* We need to strip off the leading slashes for relative
1603                  * paths, but this must be done _after_ the sorting phase. */
1604                 for (i = flist->low; i <= flist->high; i++) {
1605                         struct file_struct *file = flist->files[i];
1606
1607                         if (!file->dirname)
1608                                 continue;
1609                         while (*file->dirname == '/')
1610                                 file->dirname++;
1611                         if (!*file->dirname)
1612                                 file->dirname = NULL;
1613                 }
1614         }
1615
1616         if (prune_empty_dirs && no_dups) {
1617                 int j, prev_depth = 0;
1618
1619                 prev_i = 0; /* It's OK that this isn't really true. */
1620
1621                 for (i = flist->low; i <= flist->high; i++) {
1622                         struct file_struct *fp, *file = flist->files[i];
1623
1624                         /* This temporarily abuses the dir.depth value for a
1625                          * directory that is in a chain that might get pruned.
1626                          * We restore the old value if it gets a reprieve. */
1627                         if (S_ISDIR(file->mode) && file->dir.depth) {
1628                                 /* Dump empty dirs when coming back down. */
1629                                 for (j = prev_depth; j >= file->dir.depth; j--) {
1630                                         fp = flist->files[prev_i];
1631                                         if (fp->dir.depth >= 0)
1632                                                 break;
1633                                         prev_i = -fp->dir.depth-1;
1634                                         clear_file(fp, flist);
1635                                 }
1636                                 prev_depth = file->dir.depth;
1637                                 if (is_excluded(f_name(file, fbuf), 1,
1638                                                        ALL_FILTERS)) {
1639                                         /* Keep dirs through this dir. */
1640                                         for (j = prev_depth-1; ; j--) {
1641                                                 fp = flist->files[prev_i];
1642                                                 if (fp->dir.depth >= 0)
1643                                                         break;
1644                                                 prev_i = -fp->dir.depth-1;
1645                                                 fp->dir.depth = j;
1646                                         }
1647                                 } else
1648                                         file->dir.depth = -prev_i-1;
1649                                 prev_i = i;
1650                         } else {
1651                                 /* Keep dirs through this non-dir. */
1652                                 for (j = prev_depth; ; j--) {
1653                                         fp = flist->files[prev_i];
1654                                         if (fp->dir.depth >= 0)
1655                                                 break;
1656                                         prev_i = -fp->dir.depth-1;
1657                                         fp->dir.depth = j;
1658                                 }
1659                         }
1660                 }
1661                 /* Dump empty all remaining empty dirs. */
1662                 while (1) {
1663                         struct file_struct *fp = flist->files[prev_i];
1664                         if (fp->dir.depth >= 0)
1665                                 break;
1666                         prev_i = -fp->dir.depth-1;
1667                         clear_file(fp, flist);
1668                 }
1669
1670                 for (i = flist->low; i <= flist->high; i++) {
1671                         if (flist->files[i]->basename)
1672                                 break;
1673                 }
1674                 flist->low = i;
1675                 for (i = flist->high; i >= flist->low; i--) {
1676                         if (flist->files[i]->basename)
1677                                 break;
1678                 }
1679                 flist->high = i;
1680         }
1681 }
1682
1683 static void output_flist(struct file_list *flist)
1684 {
1685         char uidbuf[16], gidbuf[16], depthbuf[16];
1686         struct file_struct *file;
1687         const char *who = who_am_i();
1688         int i;
1689
1690         for (i = 0; i < flist->count; i++) {
1691                 file = flist->files[i];
1692                 if ((am_root || am_sender) && preserve_uid)
1693                         sprintf(uidbuf, " uid=%ld", (long)file->uid);
1694                 else
1695                         *uidbuf = '\0';
1696                 if (preserve_gid && file->gid != GID_NONE)
1697                         sprintf(gidbuf, " gid=%ld", (long)file->gid);
1698                 else
1699                         *gidbuf = '\0';
1700                 if (!am_sender)
1701                         sprintf(depthbuf, "%d", file->dir.depth);
1702                 rprintf(FINFO, "[%s] i=%d %s %s%s%s%s mode=0%o len=%.0f%s%s flags=%x\n",
1703                         who, i, am_sender ? NS(file->dir.root) : depthbuf,
1704                         file->dirname ? file->dirname : "",
1705                         file->dirname ? "/" : "", NS(file->basename),
1706                         S_ISDIR(file->mode) ? "/" : "", (int)file->mode,
1707                         (double)file->length, uidbuf, gidbuf, file->flags);
1708         }
1709 }
1710
1711 enum fnc_state { s_DIR, s_SLASH, s_BASE, s_TRAILING };
1712 enum fnc_type { t_PATH, t_ITEM };
1713
1714 /* Compare the names of two file_struct entities, similar to how strcmp()
1715  * would do if it were operating on the joined strings.
1716  *
1717  * Some differences beginning with protocol_version 29: (1) directory names
1718  * are compared with an assumed trailing slash so that they compare in a
1719  * way that would cause them to sort immediately prior to any content they
1720  * may have; (2) a directory of any name compares after a non-directory of
1721  * any name at the same depth; (3) a directory with name "." compares prior
1722  * to anything else.  These changes mean that a directory and a non-dir
1723  * with the same name will not compare as equal (protocol_version >= 29).
1724  *
1725  * The dirname component can be an empty string, but the basename component
1726  * cannot (and never is in the current codebase).  The basename component
1727  * may be NULL (for a removed item), in which case it is considered to be
1728  * after any existing item. */
1729 int f_name_cmp(struct file_struct *f1, struct file_struct *f2)
1730 {
1731         int dif;
1732         const uchar *c1, *c2;
1733         enum fnc_state state1, state2;
1734         enum fnc_type type1, type2;
1735         enum fnc_type t_path = protocol_version >= 29 ? t_PATH : t_ITEM;
1736
1737         if (!f1 || !f1->basename) {
1738                 if (!f2 || !f2->basename)
1739                         return 0;
1740                 return -1;
1741         }
1742         if (!f2 || !f2->basename)
1743                 return 1;
1744
1745         c1 = (uchar*)f1->dirname;
1746         c2 = (uchar*)f2->dirname;
1747         if (c1 == c2)
1748                 c1 = c2 = NULL;
1749         if (!c1) {
1750                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1751                 c1 = (uchar*)f1->basename;
1752                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1753                         type1 = t_ITEM;
1754                         state1 = s_TRAILING;
1755                         c1 = (uchar*)"";
1756                 } else
1757                         state1 = s_BASE;
1758         } else if (!*c1) {
1759                 type1 = t_path;
1760                 state1 = s_SLASH;
1761                 c1 = (uchar*)"/";
1762         } else {
1763                 type1 = t_path;
1764                 state1 = s_DIR;
1765         }
1766         if (!c2) {
1767                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1768                 c2 = (uchar*)f2->basename;
1769                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1770                         type2 = t_ITEM;
1771                         state2 = s_TRAILING;
1772                         c2 = (uchar*)"";
1773                 } else
1774                         state2 = s_BASE;
1775         } else if (!*c2) {
1776                 type2 = t_path;
1777                 state2 = s_SLASH;
1778                 c2 = (uchar*)"/";
1779         } else {
1780                 type2 = t_path;
1781                 state2 = s_DIR;
1782         }
1783
1784         if (type1 != type2)
1785                 return type1 == t_PATH ? 1 : -1;
1786
1787         while (1) {
1788                 if ((dif = (int)*c1++ - (int)*c2++) != 0)
1789                         break;
1790                 if (!*c1) {
1791                         switch (state1) {
1792                         case s_DIR:
1793                                 state1 = s_SLASH;
1794                                 c1 = (uchar*)"/";
1795                                 break;
1796                         case s_SLASH:
1797                                 type1 = S_ISDIR(f1->mode) ? t_path : t_ITEM;
1798                                 c1 = (uchar*)f1->basename;
1799                                 if (type1 == t_PATH && *c1 == '.' && !c1[1]) {
1800                                         type1 = t_ITEM;
1801                                         state1 = s_TRAILING;
1802                                         c1 = (uchar*)"";
1803                                 } else
1804                                         state1 = s_BASE;
1805                                 break;
1806                         case s_BASE:
1807                                 state1 = s_TRAILING;
1808                                 if (type1 == t_PATH) {
1809                                         c1 = (uchar*)"/";
1810                                         break;
1811                                 }
1812                                 /* FALL THROUGH */
1813                         case s_TRAILING:
1814                                 type1 = t_ITEM;
1815                                 break;
1816                         }
1817                         if (*c2 && type1 != type2)
1818                                 return type1 == t_PATH ? 1 : -1;
1819                 }
1820                 if (!*c2) {
1821                         switch (state2) {
1822                         case s_DIR:
1823                                 state2 = s_SLASH;
1824                                 c2 = (uchar*)"/";
1825                                 break;
1826                         case s_SLASH:
1827                                 type2 = S_ISDIR(f2->mode) ? t_path : t_ITEM;
1828                                 c2 = (uchar*)f2->basename;
1829                                 if (type2 == t_PATH && *c2 == '.' && !c2[1]) {
1830                                         type2 = t_ITEM;
1831                                         state2 = s_TRAILING;
1832                                         c2 = (uchar*)"";
1833                                 } else
1834                                         state2 = s_BASE;
1835                                 break;
1836                         case s_BASE:
1837                                 state2 = s_TRAILING;
1838                                 if (type2 == t_PATH) {
1839                                         c2 = (uchar*)"/";
1840                                         break;
1841                                 }
1842                                 /* FALL THROUGH */
1843                         case s_TRAILING:
1844                                 if (!*c1)
1845                                         return 0;
1846                                 type2 = t_ITEM;
1847                                 break;
1848                         }
1849                         if (type1 != type2)
1850                                 return type1 == t_PATH ? 1 : -1;
1851                 }
1852         }
1853
1854         return dif;
1855 }
1856
1857 /* Return a copy of the full filename of a flist entry, using the indicated
1858  * buffer or one of 5 static buffers if fbuf is NULL.  No size-checking is
1859  * done because we checked the size when creating the file_struct entry.
1860  */
1861 char *f_name(struct file_struct *f, char *fbuf)
1862 {
1863         if (!f || !f->basename)
1864                 return NULL;
1865
1866         if (!fbuf) {
1867                 static char names[5][MAXPATHLEN];
1868                 static unsigned int n;
1869
1870                 n = (n + 1) % (sizeof names / sizeof names[0]);
1871
1872                 fbuf = names[n];
1873         }
1874
1875         if (f->dirname) {
1876                 int len = strlen(f->dirname);
1877                 memcpy(fbuf, f->dirname, len);
1878                 fbuf[len] = '/';
1879                 strcpy(fbuf + len + 1, f->basename);
1880         } else
1881                 strcpy(fbuf, f->basename);
1882
1883         return fbuf;
1884 }
1885
1886 /* Do a non-recursive scan of the named directory, possibly ignoring all
1887  * exclude rules except for the daemon's.  If "dlen" is >=0, it is the length
1888  * of the dirname string, and also indicates that "dirname" is a MAXPATHLEN
1889  * buffer (the functions we call will append names onto the end, but the old
1890  * dir value will be restored on exit). */
1891 struct file_list *get_dirlist(char *dirname, int dlen,
1892                               int ignore_filter_rules)
1893 {
1894         struct file_list *dirlist;
1895         char dirbuf[MAXPATHLEN];
1896         int save_recurse = recurse;
1897         int save_xfer_dirs = xfer_dirs;
1898
1899         if (dlen < 0) {
1900                 dlen = strlcpy(dirbuf, dirname, MAXPATHLEN);
1901                 if (dlen >= MAXPATHLEN)
1902                         return NULL;
1903                 dirname = dirbuf;
1904         }
1905
1906         dirlist = flist_new(WITHOUT_HLINK, "get_dirlist");
1907
1908         recurse = 0;
1909         xfer_dirs = 1;
1910         send_directory(ignore_filter_rules ? -2 : -1, dirlist, dirname, dlen);
1911         xfer_dirs = save_xfer_dirs;
1912         recurse = save_recurse;
1913         if (do_progress)
1914                 flist_count_offset += dirlist->count;
1915
1916         clean_flist(dirlist, 0, 0);
1917
1918         if (verbose > 3)
1919                 output_flist(dirlist);
1920
1921         return dirlist;
1922 }