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