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