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